2016-07-13 240 views
1

我需要一个正则表达式来查找字符串中单词的匹配,而不管大小写,但不包含目标单词所在的大字。正则表达式获得字符串中的单词出现,但不包含包含该单词的单词

举例来说,如果目标单词是 “苹果”,正则表达式应该在以下字符串找到它:

"I found an apple."

"Apple, it's on the ground"

"That ApPLE is nice"

以下字符串:

"Many apples"

"Yellow pineapple"

我使用PHP和我已经搜索周围,发现以下正则表达式:

preg_match("\W*((?i)apple(?-i))\W*",$string) 

但似乎有一个问题,它是我得到以下错误:

Warning: preg_match(): Delimiter must not be alphanumeric or backslash

什么正确的正则表达式模式可以解决这一要求?

回答

1

您需要添加/来定界正则表达式。因此,一个解决办法是这样的:

preg_match_all('/\bapple\b/i', $string, $matches); 
$count = count($matches[0]); // group 0 are the full matches 

i修改匹配不区分大小写和g修改,而不是我们必须使用preg_match_all

+0

啊完美,谢谢! – dlofrodloh

相关问题