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.
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
}
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;
}
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.