2012-07-15 121 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);