我想使用preg_match()和checkdate()函数验证日期时间格式。我的格式是"dd/MM/yyyy hh: MM:ss"。我的代码有什么问题?
function checkDatetime($dateTime){
$matches = array();
if(preg_match("/^(d{2})-(d{2})-(d{4}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $dateTime, $matches)){
print_r($matches); echo "<br>";
$dd = trim($matches[1]);
$mm = trim($matches[2]);
$yy = trim($matches[3]);
return checkdate($mm, $dd, $yy); // <- Problem here?
}else{
echo "wrong format<br>";
return false;
}
}
//wrong result
if(checkDatetime("12-21-2000 03:04:00")){
echo "checkDatetime true<br>";
}else{
echo "checkDatetime false<br>";
}
//correct result
if(checkdate("12", "21", "2000")){
echo "checkdate true<br>";
}else{
echo "checkdate false<br>";
}
输出:Array ( [0] => 12-21-2000 03:04:00 [1] => 12 [2] => 21 [3] => 2000 [4] => 03 [5] => 04 [6] => 00 )
checkDatetime false
checkdate true
if(checkDatetime("12-21-2000 03:04:00"))
导致
$dd = 12
$mm = 21
$yy = 2000
然后调用return checkdate($mm, $dd, $yy);
,相当于return checkdate(21, 12, 2000);
很明显,$mm
不能是21,但我不能说如果你传递错误的格式checkDatetime
,或者如果你在正则表达式中解析它是错误的。