How to validate a regex with PHP
php, regex, validation
Solution
Here's an idea (demo):
function is_valid_regex($pattern)
{
return is_int(@preg_match($pattern, ''));
}
preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match.
preg_match() returns FALSE if an error occurred.
And to get the reason why the pattern isn't valid, use `preg_last_error`.
Problem
I want to be able to validate a user's inputted regex, to check if it's valid or not. First thing I found with PHP's `filter_var` with the `FILTER_VALIDATE_REGEXP` constant but that doesn't do what I want since it must pass a regex to the options but I'm not regex'ing against anything so basically it's just checking the regex validity. But you get the idea, how do I validate a user's inputted regex (that matches against nothing). Example of validating, in simple words: ``` $user_inputted_regex = $_POST['regex']; // e.g. /([a-z]+)\..*([0-9]{2})/i if(is_valid_regex($user_inputted_regex)) { // The regex was valid } else { // The regex was invalid } ``` Examples of validation: ``` /[[0-9]/i // invalid //(.*)/ // invalid /(.*)-(.*)-(.*)/ // valid /([a-z]+)-([0-9_]+)/i // valid ```