Search code examples
phpregexpreg-match

PHP Invert/Negate Regex Pattern


I have the below string and I'm trying to do a preg_replace on anything that doesn't match the 12c version number using a regular expression.

You can see the working match

The expression I'm using matches the 12c string format but I can't seem to figure out how to or if it's possible to invert/negate the regex match so instead of replacing the 12c, replace everything but the 12c so that only 12c of 11g etc is returned by the preg_match function.

Code:

preg_match('/(\s[0-9]{2}[a-z]{1}\s)/', '', 'Oracle Database 12c Enterprise Edition Release 12.1.0.0.2 - 64bit Production with the Partitioning, OLAP, Data Mining and Real Application Testing option');

Pattern:

/(\s[0-9]{2}[a-z]{1}\s)/ 

String:

Oracle Database 12c Enterprise Edition Release 12.1.0.0.2 - 64bit Production with the Partitioning, OLAP, Data Mining and Real Application Testing option

Solution

  • If I understood correctly, you want to get the text matched with the pattern:

    if (preg_match('/([0-9]{2}[a-z]{1})/', 'Oracle Database 12c Enterprise Edition Release 12.1.0.0.2 - 64bit Production with the Partitioning, OLAP, Data Mining and Real Application Testing option', $m))
      echo $m[1]; // 12c