2013-08-19 45 views
1

這與在字符串內部找到子字符串的所有位置稍有不同,因爲我希望它能夠與可能後跟空格,逗號,半字的單詞一起使用 - 冒號,冒號,感嘆號和其他標點符號。PHP查找字符串中特定單詞的所有出現位置

我有以下功能找到一個子的所有位置:

function strallpos($haystack,$needle,$offset = 0){ 
    $result = array(); 
    for($i = $offset; $i<strlen($haystack); $i++){ 
     $pos = strpos($haystack,$needle,$i); 
     if($pos !== FALSE){ 
      $offset = $pos; 
      if($offset >= $i){ 
       $i = $offset; 
       $result[] = $offset; 
      } 
     } 
    } 
    return $result; 
} 

問題是,如果我試圖找到串「我們」的所有位置,它將返回發生的位置在「招股說明書」或「含有」等。

有沒有什麼辦法可以防止這種情況?可能使用正則表達式?

謝謝。 斯特凡

+0

試試這個http://php.net/manual/de/function.preg-match-all。 php – Jurik

+0

它不會返回找到的匹配的位置。 –

+0

[str_word_count()](http://php.net/manual/en/function.str-word-count.php),格式參數爲2;然後是一個[array_filter()](http://php.net/manual/en/function.array-filter.php)關於你想要檢查的字將是正則表達式的替代方案 –

回答

1

只是爲了證明非正則表達式的替代

$string = "It behooves us all to offer the prospectus for our inclusive syllabus"; 
$filterword = 'us'; 

$filtered = array_filter(
    str_word_count($string,2), 
    function($word) use($filterword) { 
     return $word == $filterword; 
    } 
); 
var_dump($filtered); 

在$的鑰匙過濾是關閉的等位置

如果你想不區分大小寫,更換

return $word == $filterword; 

return strtolower($word) == strtolower($filterword); 
+0

非常感謝。這很有魅力。 –

3

你可以用preg_match_all捕獲偏移:

$str = "Problem is, if I try to find all positions of the substring us, it will return positions of the occurrence in prospectus or inclusive us us"; 
preg_match_all('/\bus\b/', $str, $m, PREG_OFFSET_CAPTURE); 
print_r($m); 

輸出:

Array 
(
    [0] => Array 
     (
      [0] => Array 
       (
        [0] => us 
        [1] => 60 
       ) 
      [1] => Array 
       (
        [0] => us 
        [1] => 134 
       ) 
      [2] => Array 
       (
        [0] => us 
        [1] => 137 
       ) 
     ) 
) 
相關問題