user1094128
user1094128

Reputation: 461

PHP Regular Expression - Detect if string contains a word but not within another

I have a system written in PHP which aggregates records from a number of databases in to one. When doing this I need to detect if each record is ABNORMAL and if it is, flag it as being so.

To do this I need a pattern for preg_match() so it will return false if the given string contains the word NORMAL but not ABNORMAL. The string given may be over multiple lines.

The problem I am having is that the word ABNORMAL contains the word NORMAL.

Can anyone help?

Upvotes: 0

Views: 2703

Answers (1)

Madara's Ghost
Madara's Ghost

Reputation: 174977

Use the word boundry character \b:

preg_match("|\bNORMAL\b|", $subject);

Note that it is case sensitive, the case insensitive version is this:

preg_match("|\bNORMAL\b|i", $subject);

Though if you have control over you database, you might want to use 0 and 1 (or at least N and A) instead of NORMAL and ABNORMAL.

Upvotes: 3

Related Questions