2016-07-13 239 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

相關問題