Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a regex with PHP

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
like image 541
MacMac Avatar asked Apr 06 '12 19:04

MacMac


People also ask

How do you check if a regular expression is valid or not?

new String(). matches(regEx) can be directly be used with try-catch to identify if regEx is valid. While this does accomplish the end result, Pattern. compile(regEx) is simpler (and is exactly what will end up happening anyway) and doesn't have any additional complexity.

Does PHP support regEx?

Like PHP, many other programming languages have their own implementation of regular expressions. This is the same with other applications also, which have their own support of regexes having various syntaxes.

Which function is used for search regular expression for validation purpose in PHP?

PHP's Regexp PERL Compatible Functions The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise. The preg_match_all() function matches all occurrences of pattern in string.


1 Answers

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.

like image 188
Alix Axel Avatar answered Sep 28 '22 06:09

Alix Axel