hoz*_*zza 4 php regex reverse if-statement preg-match
if(preg_match("/" . $filter . "/i", $node)) {
echo $node;
}
Run Code Online (Sandbox Code Playgroud)
此代码过滤变量以决定是否显示它.$ filter的示例条目是"office"或"164(.*)976".
我想知道是否有一种简单的说法:如果$ filter与$ node不匹配.以正则表达式的形式?
所以......不是"if(!preg_match",而是更多的$ filter ="!office"或"!164(.*)976"但是一个有效吗?
Tim*_*ker 10
如果您肯定想要使用"负正则表达式"而不是简单地反转正正则表达式的结果,则可以执行此操作:
if(preg_match("/^(?:(?!" . $filter . ").)*$/i", $node)) {
echo $node;
}
Run Code Online (Sandbox Code Playgroud)
如果字符串中不包含正则表达式/子字符串,则匹配该字符串$filter.
说明:(以office我们的示例字符串为例)
^ # Anchor the match at the start of the string
(?: # Try to match the following:
(?! # (unless it's possible to match
office # the text "office" at this point)
) # (end of negative lookahead),
. # Any character
)* # zero or more times
$ # until the end of the string
Run Code Online (Sandbox Code Playgroud)
该(?!...) 负断言是你在找什么.
要排除某个字符串出现在主题中的任何位置,您可以使用此双断言方法:
preg_match('/(?=^((?!not_this).)+$) (......)/xs', $string);
Run Code Online (Sandbox Code Playgroud)
它允许指定任意(......)主正则表达式.但是你可以把它留下来,如果你只想禁止一个字符串.