将preg_match()与REGEX表达式一起使用时,未知修饰符'(' [英] Unknown modifier '(' when using preg_match() with a REGEX expression

查看:99
本文介绍了将preg_match()与REGEX表达式一起使用时,未知修饰符'('的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用preg_match()用PHP验证DD/MM/YYYY之类的日期.这就是我的REGEX表达式:

I'm trying to validate dates like DD/MM/YYYY with PHP using preg_match(). This is what my REGEX expression looks like:

$pattern = "/^([123]0|[012][1-9]|31)/(0[1-9]|1[012])/(19[0-9]{2}|2[0-9]{3})$/";

但是使用正确的值,我会收到以下消息:

But using it with a correct value, I get this message:

preg_match():未知修饰符'('

preg_match(): Unknown modifier '('

完整代码:

    $pattern = "/^([123]0|[012][1-9]|31)/(0[1-9]|1[012])/(19[0-9]{2}|2[0-9]{3})$/";
    $date = "01/03/2011";

    if(preg_match($pattern, $date)) return TRUE;

提前谢谢

推荐答案

将表达式内的/字符转义为\/.

Escape the / characters inside the expression as \/.

$pattern = "/^([123]0|[012][1-9]|31)\/(0[1-9]|1[012])\/(19[0-9]{2}|2[0-9]{3})$/";

正如其他答案所指出的那样,最好使用表达式中未使用的另一个定界符,例如~,以避免出现倾斜牙签"效应,从而使阅读变得更加困难.

As other answers have noted, it looks better to use another delimiter that isn't used in the expression, such as ~ to avoid the 'leaning toothpicks' effect that makes it harder to read.

这篇关于将preg_match()与REGEX表达式一起使用时,未知修饰符'('的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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