[英]PHP - preg_match - Match a !word, or match !word followed by word(s)
[英]PHP Regex match sentence with word anytime when it's not a followed by another word
以下是我的句子数组
$strings = [
"I want to match docs with a word New",
"But I don't want to match docs with a phrase New York",
"However I still want to match docs with a word New which has a phrase New York",
"For example let's say there's a New restaraunt in New York and I want this doc to be matched."
]
我想将上面的句子与单词new
string匹配。 但是当new
后面跟着york
时,我不想匹配这句话。 我希望能够在某个小的字距N
之内匹配单词B
/后面没有的单词A
不是紧挨在“ A”之后。
我如何使用正则表达式获得预期的结果?
具有负前瞻性的正则表达式应该可以解决问题(请访问此链接以获取有效的演示):
.*[Nn]ew(?! [Yy]ork).*
从PHP
实现的角度来看,可以如下使用preg_match函数 :
$strings = [
"I want to match docs with a word New",
"But I don't want to match docs with a phrase New York",
"However I still want to match docs with a word New which has a phrase New York",
"For example let's say there's a New restaraunt in New York and I want this doc to be matched."
];
foreach ($strings as $string) {
echo preg_match('/.*new(?! york).*/i', $string)."\n";
}
输出为:
1 -> Match
0 -> Discarded
1 -> Match
1 -> Match
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.