繁体   English   中英

PHP Regex可以在句子后面没有单词时随时将单词与单词匹配

[英]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

这应该工作:

/(new[^ ?york])|(a[^b])/gi

DEMO

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM