2011-06-07 69 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,但這應該指向您在正確的方向。

相關問題