简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM