Hosh Sadiq Hosh Sadiq - 2 years ago 77
PHP Question

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_match('/[a-z]/', 'test');
preg_match('invalid regex', 'test');

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

Any ideas?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download