如何在没有意外匹配的情况下在 PHP 的字符串中查找整个单词? [英] How to find a whole word in a string in PHP without accidental matches?

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

问题描述

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

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

我知道听起来很简单,但是当 command 关键字也可能是另一个词的一部分时,问题就来了.

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 这样的整个词的出现,而如果作为另一个词(如 CHECKSOUND)的一部分找到,则忽略出现的 SOUND?

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/a>:

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

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

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

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

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