avetisk avetisk - 11 months ago 66
PHP Question

How to check if a string is a valid PCRE?

I need to check if a string is a valid regex.

Is there any way to do it without having performance issues?

N.B: I want to check it BEFORE using it, preg_last_error() is not what I'm looking for.

Answer Source

The suggested preg_last_error won't work for you because it only return PCRE runtime errors, not compilation faults - in the latter case all you get is a php warning ("Compilation failed"). A clean way to work around this is to install an error-to-exception error handler, and then compile the pattern within a try-catch block:

try {
    preg_match($pattern, "...");
} catch(ErrorException $e) {
   // something is wrong with the pattern