PHP正则表达式在任何时候与单词匹配时,如果它不是后跟另一个单词

时间:2018-03-11 12:46:52

标签: php regex

以下是我所拥有的一系列句子

$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 字符串相匹配。但是,当 new 后跟 york 时,我不希望与句子匹配。我希望能够匹配在某个小字距离A内没有预先/后跟字B的任何字N。不在'A'旁边。

如何使用正则表达式实现预期结果?

2 个答案:

答案 0 :(得分:3)

具有负向前瞻的正则表达式应该可以解决问题(访问this link进行工作演示):

.*[Nn]ew(?! [Yy]ork).*

PHP实施的角度来看,您可以使用preg_match function,如下所示:

$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

答案 1 :(得分:0)

这应该有效:

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

DEMO