0

我有以下变量:

$texttofind = "story of a test";
$paragraph  = "the story of a test and a test paragraph used for
               testing the story of a test paragraph";

我想preg_match();用来返回计数,在这种情况下是 2。有什么想法吗?

4

1 回答 1

8

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

echo 'Found texttofind ' . substr_count($paragraph, $texttofind) . ' times';

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

echo preg_match_all('/' . preg_quote($texttofind, '/') . '/', $paragraph);
于 2012-07-15T21:57:01.237 回答