2012-07-15 122 views
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"; 

我想用preg_match();返回计数,在这种情况下为2。任何想法?

+0

'preg_match_all'默认返回发生次数。 – hjpotter92 2012-07-15 21:58:30

回答

8

没有必要对正则表达式,只需使用substr_count

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

如果你真的想使用正则表达式,你可以使用下面的(速度较慢,和不必要的复杂)的表达:

echo preg_match_all('/' . preg_quote($texttofind, '/') . '/', $paragraph);