简体   繁体   中英

PHP Date format question

Some folks helped me on How to check the data format in PHP post but I need to check two date formats MM-DD-YYYY and DD-MM-YY instead of one. Do I need to setup two regular expression???? Thanks for the help!!!

$date1=05/25/2010;    
$date2=25/05/10;    //I wish both of them would pass 

$date_regex = '!^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$!';

if (preg_match($date_regex, $date1)) {
  do something    
}

if (preg_match($date_regex, $date2)) {  // need second Reg. expression??
  do something    
}

Your regex

$date_regex = '!^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$!';

matches MM-DD-YYYY format.

The other you want to match is simple

$date_regex2 = '!^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.]\d\d$!';

You could just check if either is true.

if(preg_match($date_regex,$date) or preg_match($date_regex2,$date)){
  //match
}

Or you could combine them using

$mmddyyyy = '!^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$!';
$mmddyy = '!^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.]\d\d$!';
$regex = "($mmddyyyy|$mmddyy)";

if(preg_match($regex,$date){
  //match
}

Not the most elegant regex but it shold work just fine.

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