[英]php regex match a word but don't match these other ones
我正在嘗試使用帶有正則表達式的 PHP 對 pipe 配件列表進行排序,我知道如何匹配多個單詞,但我不知道如何不匹配單詞。 我需要它不匹配“螺栓”和“螺母”(帶或不帶 s)。
簡單排序列表
0 - 2"x6" 黑色奶嘴
0 - 1/2x4 黑色奶嘴
20 - 3/4" x 3/8" 黑色襯套。
10 - 3/4" 黑塞螺紋
0 - 7/8 x 3 3/4 黑色螺栓
0 -7/8 黑堅果
if(preg_match('/black|union/', $_POST["fitting_name$x"])){
echo "show results";
}
似乎我需要查看我嘗試過的負前瞻.(?!bolts)
也沒有點,但對我不起作用。 我嘗試了其他一些東西,但到了一個地步,我只是向它扔東西,希望能粘住一些東西。
我真的不擅長正則表達式,所以我可能已經看到了正確的方法,但無法弄清楚如何讓它發揮作用。 也感謝您提供的任何幫助。
您可以使用負前瞻:
/^(?!.*\b(bolt|nut)s?\b).*(black|union)/
/ : Starting delimiter
^ : Matches the start of the string
(?! : Start of negative lookahead
.* : Matches any character 0 or more times
\b : Matches a word boundary before the target word
(bolt|nut) : Literal match "bolt" OR "nut"
s? : Matches an optional "s"
\b : Matches a word boundary after the target word
) : End of negative lookahead
.* : Match any charachter 0 or more times
(black|union) : Literal match "black" OR "union"
/ : Ending delimiter
在單詞的任一側使用\b
意味着您不會意外過濾掉包含單詞bolt|nut
的單詞,例如: bolted flange
。
$stringList = [
'0 - 2"x6" black nipple',
'0 - 1/2x4 black nipple',
'20 - 3/4" x 3/8" black bushing.',
'10 - 3/4" black plugs thread',
'0 - 7/8 x 3 3/4 black bolts',
'0 -7/8 black nuts'
];
foreach($stringList as $string){
var_dump(
preg_match('/^(?!.*\b(bolt|nut)s?\b).*(black|union)/', $string)
);
}
/* Output...
int(1)
int(1)
int(1)
int(1)
int(0)
int(0)
i.e. matches for all but the last 2!
*/
您可以考慮使用類似的模式
/\b(?:black|unions?)\b(?!.*\b(?:bolt|nut)s?\b)/
如果需要,在最后一個/
之后添加i
以使其不區分大小寫。 請參閱正則表達式演示。
詳情:
\b
- 單詞邊界(?:black|unions?)
- black
, union
或unions
\b
- 單詞邊界(?.?*\b(:?bolt|nut)s?\b)
- 如果在當前位置的右側有
.*
- 盡可能多的除換行符以外的任何零個或多個字符\b(?:bolt|nut)s?\b
- bolt
/ bolts
, nut
/ nuts
作為整個詞。這種模式應該有效: ^(?.?*bolts.\b|?*nuts.\b).*$
(我用bolt
替換了blot
!)它實際上使用負前瞻,但考慮到可能有更多字母.*
在單詞bolt
或nut
之前, s?
考慮到使用 0 次或 1 次的復數形式, \b
匹配單詞的結尾,因此單詞nutss
仍然匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.