0

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    
}
2
  • 1
    Erm, you should put your dates into quotes. Otherwise 05/25/2010 is just an arithmetic expression (05 divided by 25 divided by 2010). Commented Jul 24, 2010 at 19:37
  • I know. In my application, I use mktime. my code is only for demo. purpose... Commented Jul 24, 2010 at 19:38

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.