我有一个字符串,需要检查列表中的任何单词是否在字符串中。 我的列表看起来像这样:
$keywords = array(
"l.*ion",
"test",
'one',
'two',
'three'
);
This is my lion
然后我需要返回true
。This is my lotion
然后我需要返回true
。This is my dandelion
然后返回false
。This is my location
然后返回true
。This is my test
然后返回true
。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
时,它返回一个值。
我究竟做错了什么?我期待一个数字值,如果它的真实和错误,如果它的错误。
在你目前的正则表达式\bl.*ion|test|one|two|three\b
中,第一个\b
只影响第一个选择,而最后一个\b
只影响最后一个选择。
此外,由于您只想限制关键字与单个单词的匹配,因此您不能依赖.*
模式,因为.
匹配任何字符而不是换行符。
你应该使用\S*
(匹配0+非空格字符,也包括标点符号)或\w*
(匹配0+字母,数字和_
)。
所以,你需要做两件事:1)重新定义$keywords
数组和2)当implode
ing对替代品进行分组时,在替代品周围使用分组构造,以便第一个和最后一个\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
和\b
s适用于所有替代品。见this regex demo。