PHP查找字符串中特定单词的所有出现位置

时间:2013-08-19 13:50:56

标签: php regex arrays substring words

这与查找字符串中子字符串的所有位置略有不同,因为我希望它可以使用空格,逗号,分号,冒号,句号,感叹号和其他标点符号后面的单词。

我有以下函数来查找子字符串的所有位置:

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; 
}

问题是,如果我试图查找子字符串“us”的所有位置,它将在“招股说明书”或“包含性”等中返回该事件的位置。

有什么方法可以阻止这种情况吗?可能使用正则表达式?

感谢。 斯蒂芬

2 个答案:

答案 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
                )
        )
)

答案 1 :(得分: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);

其中$ filtered的键是偏移位置

如果您不想使用大小写,请替换

return $word == $filterword;

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