简体   繁体   中英

Regular expression with preg_match

what is problem with the following pattern ??

~(?P<day>[1-9]{1,2})[.](?P<month>[1-9]{1,2})[.](?P<year>[0-9]{1,4})~

i want to allow following formats..

21.12.2012
21.8.2012 // not 21.08.2012

but it also allows..

2012.12.12
12.12.12

Please help...

Thank you, Hardik

You forgot to anchor the regex. Also, if you only want to allow four-digit years, you have to make that explicit:

~^(?P<day>[0-9]{1,2})[.](?P<month>[0-9]{1,2})[.](?P<year>[0-9]{4})$~

^ and $ only match at the start and end of the string, ensuring that your regex doesn't match the 12.12.12 substring in 2012.12.12 .

If you want to forbid leading zeroes, use

~^(?P<day>[1-9][0-9]?)[.](?P<month>[1-9][0-9]?)[.](?P<year>[0-9]{4})$~

Of course, this doesn't do any sanity checking (99.99.9999 passes this regex), but checking for a valid date is something you shouldn't be doing with a regex anyway .

Try this:

$regex = '#^[0-9]{2}.[1-9][0-9]{0,1}.[0-9]{4}$#';

It should allow the 2 first formats, not the others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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