Is there any way to do this, without using the error control operator on @preg_match
? :)
Because PHP requires that patterns are wrapped between a character, I was thinking to do it this way:
- Get the first character.
Find the last occurence of this character in the string with:
$rpos = strrpos($string, $string[0]);
Get the modifier list:
$mods = substr($rpos, strlen($string));
- Find out if there are any invalid modifiers in this list. If there are return false, otherwise regex appears to be valid.
How reliable is this solution? Are there any better ones?
/(/
would pass your test, but isn't a valid regex because it contains an unmatched parenthesis. Also keep in mind that some regexes may be valid, but will consume an unreasonable amount of time or memory to run.filter_var
method.