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

Ste*_*unn 1 php regex arrays words substring

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

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

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; 
}
Run Code Online (Sandbox Code Playgroud)

问题是,如果我尝试查找子字符串“us”的所有位置,它将返回“prospectus”或“inclusive”等中出现的位置。

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

谢谢。斯特凡

Tot*_*oto 7

您可以使用 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);
Run Code Online (Sandbox Code Playgroud)

输出:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => us
                    [1] => 60
                )
            [1] => Array
                (
                    [0] => us
                    [1] => 134
                )
            [2] => Array
                (
                    [0] => us
                    [1] => 137
                )
        )
)
Run Code Online (Sandbox Code Playgroud)