2017-06-12 92 views
0

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

任何因为剧本需要检测只有完整的单词是无益的:
if (strpos($desc, $row['phrase']) !== false) 
{ 
    // action 
} 

因为公司包含的子串该脚本将返回TRUE。

该公司正在

不包含单词:任何

任何变化

确实包含着一句话: “任何”。我如何编辑strpos函数来仅搜索完整的单词,即不是它们的一部分?

谢谢。

+0

看这里https://stackoverflow.com/questions/4325956/how-to-find-a-whole-word-in-a-string-in-php-without-accidental-matches – EstevaoLuis

+1

词通常是由空格拆分所以.... strpos($ desc,“”。 $ row ['phrase']。 “”)' – Andreas

+0

@ slevy1你为什么认为重复是错误的。它使用\ b这是字 – Andreas

回答

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); 

进行请注意,我写我的手机上这个答案,所以我可以在上面的图案都犯了一个错误