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:
$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开发者_JAVA技巧?[1-9]|1[0-2])[\/\.- ](19|20)\d{2}$/';
Which regex do u use to validate your date in gg/mm/aaaa format?
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 .
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)/"
精彩评论