phpregexpreg-match

Test if a string is regex


Is there a good way of test if a string is a regex or normal string in PHP?

Ideally I want to write a function to run a string through, that returns true or false.

I had a look at preg_last_error():

<?php
preg_match('/[a-z]/', 'test');
var_dump(preg_last_error());
preg_match('invalid regex', 'test');
var_dump(preg_last_error());
?>

Where obviously first one is not an error, and second one is. But preg_last_error() returns int 0 both times.

Any ideas?


Solution

  • The only easy way to test if a regex is valid in PHP is to use it and check if a warning is thrown.

    ini_set('track_errors', 'on');
    $php_errormsg = '';
    @preg_match('/[blah/', '');
    if($php_errormsg) echo 'regex is invalid';
    

    However, using arbitrary user input as a regex is a bad idea. There were security holes (buffer overflow => remote code execution) in the PCRE engine before and it might be possible to create specially crafted long regexes which require lots of cpu/memory to compile/execute.