Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Example #2 from the documentation of preg_match:

/* The  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("/web/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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...