簡體   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