2011-01-06 107 views
0

我使用简单的preg_match_all来查找文本中单词列表的出现。如何匹配完整的单词?

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

但是,这也匹配abcword123等词的子集。我需要它找到word1,word2word3,当它们仅作为完整单词出现时。请注意,这并不总是意味着它们在两侧用空格分隔,它可以是逗号,分号,句点,感叹号,问号或其他标点符号。

回答

3

如果你正在寻找匹配“word1”,“word2”,“word3”等只有使用in_array总是更好。正则表达式是超级强大的,但它也需要很多的CPU功能。所以尽量避免它的时候曾经可能

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

检查PHP: in_array - Manual的更多信息,in_array

如果你想使用正则表达式只能尽力

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

如果你想要得到的东西像"this statement has word1 in it",然后使用"\b"就像

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

更多此处PHP: Escape sequences - Manual搜索\b

1

尝试:

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

您可以使用\b匹配单词边界。所以你想用/\b(word1|word2|word3)\b/作为你的正则表达式。