如何在PHP中找到字符串中的整个单词而不会意外匹配? [英] How to find a whole word in a string in PHP without accidental matches?

查看:88
本文介绍了如何在PHP中找到字符串中的整个单词而不会意外匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解析一个字符串命令数组,我需要知道一个字符串是否包含特定的关键字.

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.

例如:

CHECKSOUND
SOUND
CHECK

因此,我需要检查当前行是否具有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)

然后它可能在SOUND之前找到CHECKSOUND,因此无法正确解析.

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

问题:

有没有办法只找到整个单词(如SOUND)的出现,而忽略出现的SOUND(如果它是另一个单词,如CHECKSOUND的一部分)?

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.

推荐答案

您可以使用正则表达式轻松实现目标.

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

preg_match 的文档中的示例#2:

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.";
 }

请注意,上面的示例使用了i修饰符,这使得对"web"的搜索不区分大小写.

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

这篇关于如何在PHP中找到字符串中的整个单词而不会意外匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆