2

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.

avetisk
  • 11,651
  • 4
  • 24
  • 37

3 Answers3

2

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 
}
user187291
  • 53,363
  • 19
  • 95
  • 127
0

In php I'm using the following function to test the validity of a pcre:

function BoolTestPregRegex($Regex)
{
    $Result = @preg_match("/$Regex/", '1234567890123');

    if ($Result === false)
        return false;
    else
        return true;

}
Paolo Benvenuto
  • 385
  • 4
  • 15
0

The best way is usually to just try and run/compile it with your Regex engine and check for errors. I wouldn't worry about performance before you need to.

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145