本文介绍了PHP 反向 Preg_match的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

if(preg_match("/" . $filter . "/i", $node)) {
    echo $node;
}

此代码过滤变量以决定是否显示它.$filter 的示例条目是office"或164(.*)976".

This code filters a variable to decide whether to display it or not. An example entry for $filter would be "office" or "164(.*)976".

我想知道是否有一个简单的方法说:如果$filter在$node中不匹配.以正则表达式的形式?

I would like to know whether there is a simple way to say: if $filter does not match in $node. In the form of a regular expression?

所以...不是if(!preg_match",而是更多的 $filter = !office" 或!164(.*)976",而是一个有效的?

So... not an "if(!preg_match" but more of a $filter = "!office" or "!164(.*)976" but one that works?

推荐答案

如果您确实想使用负正则表达式"而不是简单地反转正正则表达式的结果,则可以这样做:

This can be done if you definitely want to use a "negative regex" instead of simply inverting the result of the positive regex:

if(preg_match("/^(?:(?!" . $filter . ").)*$/i", $node)) {
    echo $node;
}

将匹配一个字符串,如果它不包含 $filter 中的正则表达式/子字符串.

will match a string if it doesn't contain the regex/substring in $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

这篇关于PHP 反向 Preg_match的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:15