How to match full words?

房东的猫 提交于 2019-12-25 03:09:22

问题


I use a simple preg_match_all to find the occurrence of a list of words in a text.

$pattern = '/(word1|word2|word3)/';
$num_found = preg_match_all( $pattern, $string, $matches );

But this also match subset of words like abcword123. I need it to find word1, word2 and word3 when they're occurring as full words only. Note that this doesn't always mean that they're separated by spaces on both sides, it could be a comma, semi-colon, period, exclamation mark, question mark, or another punctuation.


回答1:


IF you are looking to match "word1", "word2", "word3" etc only then using in_array is always better. Regex are super powerful but it takes a lot of cpu power also. So try to avoid it when ever possible

$words = array ("word1", "word2", "word3" );
$found = in_array ($string, $words);

check PHP: in_array - Manual for more information on in_array

And if you want to use regex only try

$pattern = '/^(word1|word2|word3)$/';
$num_found = preg_match_all( $pattern, $string, $matches );

And if you want to get something like "this statement has word1 in it", then use "\b" like

$pattern = '/\b(word1|word2|word3)\b/';
$num_found = preg_match_all( $pattern, $string, $matches );

More of it here PHP: Escape sequences - Manual search for \b




回答2:


Try:

$pattern = '/\b(word1|word2|word3)\b/';
$num_found = preg_match_all( $pattern, $string, $matches );



回答3:


You can use \b to match word boundaries. So you want to use /\b(word1|word2|word3)\b/ as your regex.



来源:https://stackoverflow.com/questions/4611767/how-to-match-full-words

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