开发者

How to match full words?

开发者 https://www.devze.com 2023-02-02 12:31 出处:网络
I use a simple preg_match_all to find the occurrence of a list of words in a text. $pattern = \'/(word1|word2|word3)/\';

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, $m开发者_如何学Pythonatches );

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.


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


Try:

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消