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?
The simplest way to test if a string is a regex is:
if( preg_match("/^\/.+\/[a-z]*$/i",$regex))
This will tell you if a string has a good chance of being intended to be as a regex. However there are many string that would pass that check but fail being a regex. Unescaped slashes in the middle, unknown modifiers at the end, mismatched parentheses etc. could all cause problems.
The reason preg_last_error
returned 0 is because the "invalid regex" is not: