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
  • 10,761
  • 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
  • 52,425
  • 19
  • 93
  • 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
  • 357
  • 2
  • 14
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
  • 45,503
  • 23
  • 111
  • 144