1

これは、文字列内の部分文字列のすべての位置を見つけることとは少し異なります。これは、スペース、コンマ、セミコロン、コロン、ピリオド、感嘆符、およびその他の句読点が続く可能性のある単語を処理するためです。

部分文字列のすべての位置を見つける次の関数があります。

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」のすべての位置を見つけようとすると、「prospectus」または「inclusive」などの出現位置が返されることです.

これを防ぐ方法はありますか?おそらく正規表現を使用していますか?

ありがとう。ステファン

4

2 に答える 2

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

出力:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => us
                    [1] => 60
                )
            [1] => Array
                (
                    [0] => us
                    [1] => 134
                )
            [2] => Array
                (
                    [0] => us
                    [1] => 137
                )
        )
)
于 2013-08-19T14:14:16.090 に答える
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);
于 2013-08-19T14:22:08.867 に答える