count executions of test in string php,not test123 or testabc

2q5ifsrm  于 2023-04-04  发布在  PHP
关注(0)|答案(1)|浏览(106)

我使用的代码:

$text = 'This is test22 is a test11 abc test mlk'
result= substr_count($text, 'test',0,0)

result = 3;
但我的期望输出= 1;
我只想计算单词test的出现次数,而不是testaaatest123
谢谢你

xytpbqjk

xytpbqjk1#

单独的字符串检查不能做到这一点。我会使用正则表达式来实现这一点。使用单词边界和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('/\btest\b/', '', $text, -1, $count);

相关问题