php preg_match返回计数

cpp*_*pit 0 php preg-match

我有以下几个变量:

$texttofind = "story of a test";
$paragraph  = "the story of a test and a test paragraph used for
               testing the story of a test paragraph";
Run Code Online (Sandbox Code Playgroud)

我想preg_match();用来返回计数,在这种情况下将是2.任何想法?

phi*_*hag 8

不需要正则表达式,只需使用substr_count:

echo 'Found texttofind ' . substr_count($paragraph, $texttofind) . ' times';
Run Code Online (Sandbox Code Playgroud)

如果您确实想使用正则表达式,则可以使用以下(较慢且不必要的复杂)表达式:

echo preg_match_all('/' . preg_quote($texttofind, '/') . '/', $paragraph);
Run Code Online (Sandbox Code Playgroud)