views:

28

answers:

3

I'm creating an administration panel that has regex's submitted to it. Any ideas on how I would go about validating the submitted regex's to see if they work. When I say "see if they work" I mean if the regex's are valid and compile properly, not that they actually match data or not?

FYI, This would be in PHP.

+1  A: 

Solved it myself after checking the docs.

preg_match('/'.$pattern.'/', 'foobar foobar foobar');
if(preg_last_error() === PREG_NO_ERROR)
{
    // ok
}
buggedcom
This might print an error depending on your config settings. Check my answer for how to suppress the warning output.
webbiedave
good point. cheers.
buggedcom
+2  A: 

preg_match returns boolean false on error so it's a simple matter of checking the return value (make sure you use the === not ==) and suppress the warning output:

if (@preg_match('/some expression/', '') === false) {   
    // bad regex
}
webbiedave
+1  A: 

Another solution that wont throw a warning but uses ugly error supressing...

$good_re = '~\d+~';
$bad_re = '@#$';

$good_check = @preg_match( $good_re, 'asdd' );
var_dump($good_check);

$bad_check = @preg_match( $bad_re, 'asdd' );
var_dump($bad_check);
Galen