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
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.