我試圖做一個粗略的日期驗證1897年6月13日格式與此,但它始終無效,無論我輸入的日期。preg_match日期驗證不起作用
$date = $_GET['date'];
if (preg_match('/^[0-9]{1,2} [Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec] [0-9]{4}$/', $date)) {
$date = date("Ymd", strtotime($date));
echo $date;
}
else
echo 'invalid';
要稍微闡述,日期可以在該格式,或1965年9月或1989年剛當後兩者,我需要用零來代替缺失值。例如。 19650900或19890000.所以我首先要做一個粗略的檢查和轉換。如果無效,那麼我需要手動用零替換丟失的值。我完整的代碼會是這個樣子:
function conv_date($date)
{
if (preg_match('/^[0-9]{1,2} [Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec] [0-9]{4}$/', $date))
return date("Ymd", strtotime($date));
$date = str_replace('?',' ',$date);
$words = explode(' ', $date);
$year = array_pop($words);
$month = array_pop($words);
$day = array_pop($words);
if ($year < 1600 || $year > date("Y"))
return '';
if (empty($day) || $day < '1' || $day > '31')
$day = '00';
else
$day = substr('0'.$day,-2);
if (!empty($month))
$month = str_replace(array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'),
array('01','02','03','04','05','06','07','08','09','10','11','12',),$month);
if ($month < '01' || $month > '12')
$month = '00';
return $year.$month.$day;
}
http://codepad.viper-7.com/kumfGM –