Php find word in text using regular expression

拜拜、爱过 提交于 2021-02-20 03:49:39

问题


I want to find the whole words in text not a sub string. I have written following code.

$str = 'its so old now.';
$a   = 'so';
if (stripos($str,$a) !== false) {
 echo 'true';
} else {
 echo 'false';
}

str1 = 'its so old now.';
str2 = 'it has some issue.';

I want to find word 'so' in text. it give true in both the string. But I want true in first case only because in second string 'so' contains in 'some' words.

Thanks in advance


回答1:


\b can be used in regex to match word boundaries.

\bso\b

Should only match so when it is on it's own:

if(preg_match('/\bso\b/',$str)){
    echo "Matches!";
}

Note that preg_match returns 0 on no match and false on error so you may wish to check for these values. The above is also case insensitive. You can use /\bso\b/i to ignore case.



来源:https://stackoverflow.com/questions/37786407/php-find-word-in-text-using-regular-expression

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