简体   繁体   English

正则表达式的日期不能在PHP中工作

[英]Regex for date not working in php

This regex working in javascript doesn't work in php once the delimiters are added, throwing out a nice error: 一旦添加了定界符,此可在javascript中使用的正则表达式将无法在php中运行,并抛出一个不错的错误:

$regex = '/(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\\\d\\\\d)/';

This one neither, it even gives a compilation error! 这个都不行,甚至会给出编译错误!

$regex = '/^(0?[1-9]|[12][0-9]|3[01])[\\/\\.- ](0?[1-9]|1[0-2])[\\/\\.- ](19|20)\\d{2}$/';

Which regex do u use to validate your date in gg/mm/aaaa format? 您使用哪个正则表达式以gg / mm / aaaa格式验证您的日期?

try this: (escaping / in regexp as \\/ . I also changed order of the digit match.) 试试这个:(逃逸/在正则表达式为\\/我也改变了数字匹配的顺序。)

$regex = "/^(3[01]|[12][0-9]|0?[1-9])\/(1[012]|0?[1-9])\/((19|20)\d{2})$/";

For your second regex where you used [\\/\\.- ] this is wrong because the [\\.- ] means 'from . 对于您使用[\\/\\.- ]的第二个正则表达式,这是错误的,因为[\\.- ]表示'from . to ' to fix this - should be the very first or the last character between [] . '以解决此问题-应该是[]之间的第一个或最后一个字符。

If this is for validating, why not something like this?: 如果这是为了验证,为什么不这样呢?:

$date = date_parse_from_format('d/m/Y', '08/08/2000');

if ($date['warning_count'] || $date['error_count']) {
   // invalid date
}

It's obviously not a regular expression, but it seems simpler to manage. 它显然不是正则表达式,但似乎更易于管理。

I'm not sure what triggers warnings and what triggers errors, but a few simple tests should satisfy any curiosities. 我不确定是什么触发警告和什么是触发错误,但是一些简单的测试应该可以满足您的好奇心。

I think your problem is that you are attempting to escape the wrong slashes inside your string, which just makes it think you want to match backslashes but then it gets confused by the slashes inside your regex. 我认为您的问题是,您试图在字符串中转义错误的斜杠,这只是使其认为您要匹配反斜杠,但是正则表达式中的斜杠使它感到困惑。 Try this: 尝试这个:

"/(0?[1-9]|[12][0-9]|3[01])\\/(0?[1-9]|1[012])\\/((19|20)\\d\\d)/"

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

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