我有一个单词数组。例如,
$pattern = ['in', 'do', 'mie', 'indo'];
我想按模式将单词匹配拆分为某些方式。
输入 =
indomie
到输出 =
$ in, do, mie
$ indo, mie
有什么建议吗?
*ps 对不起英语不好。非常感谢!
最佳答案
这是一个非常有趣的问题。
输入:-
$inputSting = "indomie";
$pattern = ['in', 'do', 'mie', 'indo','dom','ie','indomi','e'];
输出:-
in,do,mie
in,dom,ie
indo,mie
indomi,e
应对这一挑战的方法
获取模式字符串长度
获取矩阵所有可能的组合
检查模式是否匹配。
如果我正确理解你的问题,那么在@V 之上。 Prince answer 仅适用于查找最大两个模式。
function sampling($chars, $size, $combinations = array()) {
if (empty($combinations)) {
$combinations = $chars;
}
if ($size == 1) {
return $combinations;
}
$new_combinations = array();
foreach ($combinations as $combination) {
foreach ($chars as $char) {
$new_combinations[] = $combination . $char;
}
}
return sampling($chars, $size - 1, $new_combinations);
}
function splitbyPattern($inputSting, $pattern)
{
$patternLength= array();
// Get the each pattern string Length
foreach ($pattern as $length) {
if (!in_array(strlen($length), $patternLength))
{
array_push($patternLength,strlen($length));
}
}
// Get all the matrix combination of pattern string length to check the probablbe match
$combination = sampling($patternLength, count($patternLength));
$MatchOutput=Array();
foreach ($combination as $comp) {
$intlen=0;
$MatchNotfound = true;
$value="";
// Loop Through the each probable combination
foreach (str_split($comp,1) as $length) {
if($intlen<=strlen($inputSting))
{
// Check whether the pattern existing
if(in_array(substr($inputSting,$intlen,$length),$pattern))
{
$value = $value.substr($inputSting,$intlen,$length).',';
}
else
{
$MatchNotfound = false;
break;
}
}
else
{
break;
}
$intlen = $intlen+$length;
}
if($MatchNotfound)
{
array_push($MatchOutput,substr($value,0,strlen($value)-1));
}
}
return array_unique($MatchOutput);
}
$inputSting = "indomie";
$pattern = ['in', 'do', 'mie', 'indo','dom','ie','indomi','e'];
$output = splitbyPattern($inputSting,$pattern);
foreach($output as $out)
{
echo $out."<br>";
}
?>
关于php - 如何使用 PHP 按模式拆分单词匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57735313/