dlofrodloh dlofrodloh - 7 months ago 24
PHP Question

Regex for getting occurrences of a word in a string but not words containing that word

I need a regex to find matches of words in a string regardless of case, but not larger words where the target word is a part of.

For instance, if the target word is "apple", the regex should find it in the following strings:

"I found an apple."

"Apple, it's on the ground"

"That ApPLE is nice"

But not the following strings:

"Many apples"

"Yellow pineapple"

I'm using PHP and I've searched around and found the following regex:


But there seems to be an issue with it as I get the following error:

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

What correct regex pattern could solve this requirement?


You need to add / to delimit the regex. So a solution could look like this:

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

The i modifier matches case-insensitive and instead of the g modifier we have to use preg_match_all.