检查字符串是否以特定单词开头,如果是,则将其拆分


Check if a string starts with certain words, and split it if it is

$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,但这应该为您指明正确的方向。