简体   繁体   English

如何使用 PHP 验证正则表达式

[英]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.我发现的第一件事是使用带有FILTER_VALIDATE_REGEXP常量的 PHP 的filter_var ,但这并没有达到我想要的效果,因为它必须将正则表达式传递给选项,但我没有正则表达式反对任何东西,所以基本上它只是检查正则表达式的有效性。

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. preg_match() 返回模式匹配的次数。 That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match.这将是 0 次(无匹配)或 1 次,因为 preg_match() 将在第一次匹配后停止搜索。

preg_match() returns FALSE if an error occurred.如果发生错误,preg_match() 返回 FALSE。

And to get the reason why the pattern isn't valid, use preg_last_error .要了解模式无效的原因,请使用preg_last_error

You would need to write your own function to validate a regex.您需要编写自己的 function 来验证正则表达式。 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!换句话说,您只能测试一个正则表达式的有效语法……这几乎可以是任何东西!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM