Search code examples
phpregexif-statementpreg-matchreverse

PHP Reverse Preg_match


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

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

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?

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


Solution

  • 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;
    }
    

    will match a string if it doesn't contain the regex/substring in $filter.

    Explanation: (taking office as our example string)

    ^          # 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