匹配字符串中的整个单词,避免意外匹配

问题描述 投票:0回答:1

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

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

例如:

CHECKSOUND
SOUND
CHECK

所以我需要检查当前行是否有CHECKSOUND、SOUND或CHECK命令。

如果我使用类似的东西:

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

那么它可能会在

CHECKSOUND
之前找到
SOUND
,从而无法正确解析。

问题

有没有一种方法可以只查找整个单词(例如 SOUND)的出现,并且如果发现 SOUND 作为另一个单词(例如 CHECKSOUND)的一部分,则忽略该出现?

我确信我在这里遗漏了一些简单的东西。

php regex validation parsing preg-match
1个回答
32
投票

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

preg_match
文档中的示例#2:

/* 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”不区分大小写。

© www.soinside.com 2019 - 2024. All rights reserved.