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
<?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
int 0 both times.
The only easy way to test if a regex is valid in PHP is to use it and check if a warning is thrown.
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.