PHP strpos - 只搜索完整的单词

时间:2017-06-12 08:00:51

标签: php strpos

如果我有一个包含单词公司的字符串,并且我希望只搜索完整的单词,例如任何,我会遇到使用strpos()的问题,如如下:

if (strpos($desc, $row['phrase']) !== false )
{
    // action
}

此脚本将返回TRUE,因为公司包含子字符串:任何,这是无用的,因为脚本只需要检测完整的字词。

该公司正在运作

不包含“任何

这个词

但是

是否任何更改

包含单词:" any"。如何编辑一个strpos函数来只搜索完整的单词,即不是它们的一部分呢?

感谢。

1 个答案:

答案 0 :(得分:0)

试试这个正则表达式。

https://regex101.com/r/Evd3iF/1

$re = '/\b[Aa]ny\b/';
$str = 'Company any any. Any, ';

If(preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0)){
        //string contains word
 }

// Print the entire match result
var_dump($matches);

可以使用

创建模式
$pattern = "/\b[" . strtoupper(Substr($word,0,1)) . strtolower(Substr($word,0,1)) . "]" . Substr($word,1);

请注意我在手机上写了这个答案,所以我可能在上面的模式中犯了错误

相关问题