2009-05-21 52 views

回答

7
$string = 'abc fox fox fox ghi xyz'; 

$substring = 'fox'; 

$substringCount = substr_count($string, $substring); 

echo '"' . $substring . '" appears in "' . $string . '" ' . $substringCount . ' times'; 
+0

Aaah。打败了我。 :) – 2009-05-21 21:50:13

0

substr_count()方法确实很不错,但如果你有更多的需求(例如只匹配整个单词)这里是使用preg_match_all()和单词边界的正则表达式版本:

$nb_of_matches = preg_match_all('/\bfox\b/', $subject); 

很简单太:-)

相关问题