测试正则表达式在PHP中是否有效 [英] Test if a regular expression is a valid one in PHP

查看:67
本文介绍了测试正则表达式在PHP中是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个表单验证类,希望在验证中包括正则表达式.因此,不能保证所提供的正则表达式有效.

I am writing a form validation class and wish to include regular expressions in the validation. Therefore, the regex provided isn't guaranteed to be valid.

如何(有效)检查正则表达式是否有效?

How can I (efficiently) check that the regex is valid?

推荐答案

在您的preg_*调用中使用该模式.如果函数返回false,则您的模式可能有问题.据我所知,这是检查regex模式在PHP中是否有效的最简单方法.

Use the pattern in your preg_* calls. If the function returns false there is likely a problem with your pattern. As far as I know this is the easiest way to check if a regex pattern is valid in PHP.

下面是指定正确类型的布尔检查的示例:

Here's an example specifying the right kind of boolean check:

$invalidPattern = 'i am not valid regex';
$subject = 'This is some text I am searching in';
if (@preg_match($invalidPattern, $subject) === false) {
    // the regex failed and is likely invalid
}

这篇关于测试正则表达式在PHP中是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆