How to find a whole word in a string in PHP withou

2020-01-27 06:08发布

问题:

Parsing an array of string commands, I need to know if a string contains a specific keyword.

Sounds simple I know, but the problem comes when the command keyword may also be part of another word.

Ex:

CHECKSOUND
SOUND
CHECK

So I need to check if the current line has the CHECKSOUND, SOUND, or CHECK command.

If I use something like:

if(stristr($line,'SOUND') == true)

Then it may find CHECKSOUND before SOUND and thus not parse correctly.

Question:

Is there a way to find only an occurrence of a whole word like SOUND and ignore the occurrence SOUND if found as part of another word like CHECKSOUND?

I am sure I am missing something simple here.

回答1:

You can use a regular expression to easily achive the goal.

Example #2 from the documentation of preg_match:

/* The \b in the pattern indicates a word boundary, so only the distinct
 * word "web" is matched, and not a word partial like "webbing" or "cobweb" */
 if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
     echo "A match was found.";
 } else {
     echo "A match was not found.";
 }

Note that the above example uses the i modifier, which makes the search for "web" case insensitive.