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

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 .


You would need to write your own function to validate a regex. You can validate it so far as to say whether it contains illegal characters or bad form, but there is no way to test that it is a working expression. For that you would need to create a solution.

But then you do realize there really is no such thing as an invalid regex. A regex is performance based. It either matches or it doesn't and that is dependent upon the subject of the test--even if the expression or its results are seemingly meaningless.

In other words, you can only test a regular expression for valid syntax...and that can be nearly anything!

链接地址: http://www.djcxy.com/p/76752.html

上一篇: 如何永久保存另一个应用程序提供的PendingIntent

下一篇: 如何用PHP验证正则表达式