PHP strpos - search only full words [duplicate]

本秂侑毒 提交于 2019-12-04 06:28:54

问题


If I have a string containing the word Company and I wish to search for only full words, such as any, I encounter a problem using strpos(), as follows:

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

This script will return TRUE because Company contains a substring: any which is unhelpful because the script needs to detect only full words.

The company is working

doesn't contain the word: any

but

Is there any change

does contain the word: "any". How may I edit a strpos function to search only full words, i.e. not part of them?

Thanks.


回答1:


Try this regex.

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

The word to pattern can be made with

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

Please note I wrote this answer on my phone, so I may have made a mistake in the above pattern



来源:https://stackoverflow.com/questions/44494263/php-strpos-search-only-full-words

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!