$str = 'foooo'; // <- true; how can I get 'foo' + 'oo' ?
$words = array(
'foo',
'oo'
);
如果$str
以数组中的一个单词开头,那么最快的方法是什么?
使用示例中的$words
和$str
:
$pieces = preg_split('/^('.implode('|', $words).')/',
$str, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
结果:
array(2) {
[0]=>
string(3) "foo"
[1]=>
string(2) "oo"
}
尝试:
<?php
function helper($str, $words) {
foreach ($words as $word) {
if (substr($str, 0, strlen($word)) == $word) {
return array(
$word,
substr($str, strlen($word))
);
}
}
return null;
}
$words = array(
'foo',
'moo',
'whatever',
);
$str = 'foooo';
print_r(helper($str, $words));
输出:
Array
(
[0] => foo
[1] => oo
)
此解决方案遍历$words
数组,并检查$str
是否以其中的任何单词开头。如果找到匹配项,则将$str
缩减为$w
并中断。
foreach ($words as $w) {
if ($w == substr($str, 0, strlen($w))) {
$str=$w;
break;
}
}
string[] MaybeSplitString(string[] searchArray, string predicate)
{
foreach(string str in searchArray)
{
if(predicate.StartsWith(str)
return new string[] {str, predicate.Replace(str, "")};
}
return predicate;
}
这将需要从C#转换为PHP,但这应该为您指明正确的方向。