Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Reverse Preg_match [duplicate]

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?

like image 314
hozza Avatar asked Dec 02 '22 02:12

hozza


2 Answers

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
like image 67
Tim Pietzcker Avatar answered Dec 15 '22 10:12

Tim Pietzcker


The (?!...) negative assertion is what you're looking for.

To exclude a certain string from appearing anywhere in the subject you can use this double assertion method:

preg_match('/(?=^((?!not_this).)+$)  (......)/xs', $string);

It allows to specify an arbitrary (......) main regex still. But you could just leave that out, if you only want to forbid a string.

like image 38
mario Avatar answered Dec 15 '22 09:12

mario