2011-06-07 68 views

回答

5

使用从你的例子$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" 
} 
+0

谢谢!你知道我该怎么做,但反过来?我的意思是检查字符串是否以 – Alex 2011-06-07 18:21:28

+3

@Alex之一结尾,如果在最终的''''符号之前删除'^'(行标记的开始)并将其替换为'$'(行尾标记) /':''/('。implode('|',$ words)。')$ /'' – Matthew 2011-06-07 19:01:36

3

尝试:

<?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 
) 
2

该溶液遍历所述$words阵列,并检查是否$str开始在它的任何单词。如果发现匹配,它会将$str减少为$w并中断。

foreach ($words as $w) { 
    if ($w == substr($str, 0, strlen($w))) { 
      $str=$w; 
      break; 
    } 
} 
1
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,但这应该指向您在正确的方向。

相关问题