简体   繁体   中英

PHP Regex match sentence with word anytime when it's not a followed by another word

Below is the array of sentences I have

$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."
] 

I want to match the above sentences with word new string in it. But I don't want match the sentence when new is followed by york . I'd like to be able to match any word A that isn't prepended/followed by word B within some small word distance N . Not immediate next to `A'.

How can I achieve expected result using regex?

A regular expression with a negative lookahead should do the trick (visit this link for a working demo):

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

On the point of view of the PHP implementation, you can use the preg_match function as follows:

$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";
}

The output is:

1 -> Match
0 -> Discarded
1 -> Match
1 -> Match

This should work:

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

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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