2010-07-24 123 views
0

有些人帮助我 How to check the data format in PHP 后,但我需要检查两个日期格式MM-DD-YYYY和DD-MM-YY而不是一个。我需要设置两个正则表达式吗?谢谢您的帮助!!!PHP日期格式问题

$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  
} 
+1

呃,你应该把你的日期放进引号中。否则'05/25/2010'只是一个算术表达式(05除以25除以2010)。 – Gumbo 2010-07-24 19:37:23

+0

我知道。在我的应用程序中,我使用mktime。我的代码仅用于演示。目的... – user401184 2010-07-24 19:38:30

回答

3

你的正则表达式

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

匹配MM-DD-YYYY格式。

要匹配其他简单

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

你可以只检查,如果以上任何一种情况。

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

或者你可以使用

$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 
} 

不是最优雅的正则表达式将它们结合起来,但它shold工作得很好。

+0

谢谢。对我来说足够好.... – user401184 2010-07-24 20:08:19