如何使用正则表达式搜索字符串是否包含列表中的至少一个单词?

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

我有一个字符串,需要检查列表中的任何单词是否在字符串中。 我的列表看起来像这样:

$keywords = array(
    "l.*ion",
    "test",
    'one',
    'two',
    'three'
);
  1. 如果我有字符串This is my lion然后我需要返回true
  2. 如果我有字符串This is my lotion然后我需要返回true
  3. 如果我有字符串This is my dandelion然后返回false
  4. 如果我有字符串This is my location然后返回true
  5. 如果我有字符串This is my test然后返回true
  6. 如果我有字符串This is my testing然后返回false

这是我的代码:

$keywords = implode($keywords,"|");
$list= "/\b$keywords\b/i";
$my_string= "This is my testing";
preg_match($list, $my_string, $matches, PREG_OFFSET_CAPTURE);
echo $matches[0][1];

但是,当我做This is my testing时,它返回一个值。 我究竟做错了什么?我期待一个数字值,如果它的真实和错误,如果它的错误。

php regex
1个回答
2
投票

在你目前的正则表达式\bl.*ion|test|one|two|three\b中,第一个\b只影响第一个选择,而最后一个\b只影响最后一个选择。

此外,由于您只想限制关键字与单个单词的匹配,因此您不能依赖.*模式,因为.匹配任何字符而不是换行符。

你应该使用\S*(匹配0+非空格字符,也包括标点符号)或\w*(匹配0+字母,数字和_)。

所以,你需要做两件事:1)重新定义$keywords数组和2)当implodeing对替代品进行分组时,在替代品周围使用分组构造,以便第一个和最后一个\b可以应用于每个替代品。

$keywords = array(
    "l\w*ion",     // <-- Here, a `\w` is used instead of .
    "test",
    'one',
    'two',
    'three'
);

$list= "/\b(?:" . implode($keywords,"|") . ")\b/i"; // <-- Here, the (?:...) groups alternatives
$my_string= "This is my testing";
if (preg_match($list, $my_string, $matches, PREG_OFFSET_CAPTURE)) {
  echo $matches[0][1];
}

PHP demo

现在,模式是\b(?:l\w*ion|test|one|two|three)\b\bs适用于所有替代品。见this regex demo

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