Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a whole word in a string in PHP without accidental matches?

Tags:

regex

php

parsing

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.

like image 259
Todd Moses Avatar asked Dec 01 '10 15:12

Todd Moses


1 Answers

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.

like image 75
Jon Avatar answered Oct 26 '22 23:10

Jon