我使用的代码:
$text = 'This is test22 is a test11 abc test mlk' result= substr_count($text, 'test',0,0)
result = 3;但我的期望输出= 1;我只想计算单词test的出现次数,而不是testaaa或test123谢谢你
result = 3;
1
test
testaaa
test123
xytpbqjk1#
单独的字符串检查不能做到这一点。我会使用正则表达式来实现这一点。使用单词边界和preg_match可以完成:
preg_match
$text = 'This is test22 is a test11 abc test mlk'; preg_match('/\btest\b/', $text, $result); echo count($result);
或者,可以使用preg_replace,它具有内置的count功能。
preg_replace
count
preg_replace('/\btest\b/', '', $text, -1, $count);
1条答案
按热度按时间xytpbqjk1#
单独的字符串检查不能做到这一点。我会使用正则表达式来实现这一点。使用单词边界和
preg_match
可以完成:或者,可以使用
preg_replace
,它具有内置的count
功能。