2012-03-28 34 views
5

我試圖使用修改預浸格式從preg_match: check birthday format (dd/mm/yyyy)匹配信用卡到期日期(YYYY-MM格式)PHP的preg_match日期格式「YYYY-MM」

if (!preg_match('/([0-9]{4})\-([0-9]{2})/', $expirationDate, $matches)) { 
     throw new Services_Payment_Exception('Card expiration date is invalid'); 
    } 

出於某種原因,這也驗證無效值,如20111-02(無效年份)。 我在這裏做錯了什麼?我想確認年份是4個位數,月是2個位數(01,02 ... 12)

回答

9

錨你的正則表達式:

preg_match('/^([0-9]{4})-([0-9]{2})$/', $expirationDate, $matches) 

你的正則表達式沒有做你所期望的,因爲它符合「0111-02」的「20111-02」串。

Anchors^$匹配輸入字符串內的特定的位置:^的字符串的開頭相匹配,並且$結束相匹配。

還要注意的是,由於它只有[]中的特殊功能,所以不需要跳過連字符。

4

使用^$錨:

if (!preg_match('/^([0-9]{4})\-([0-9]{2})$/', $expirationDate, $matches)) { 
    throw new Services_Payment_Exception('Card expiration date is invalid'); 
} 

確保整個字符串相匹配。

在你的例子20111-02匹配,因爲它匹配20111-020111-02部分。

2

它匹配0111-02,它符合您的要求。

變化:

'/([0-9]{4})\-([0-9]{2})/' 

到:

'/^([0-9]{4})\-([0-9]{2})$/' 

所以只對字符串的全部檢查。

2

試試這個: if (!preg_match('/^([0-9]{4})\-([0-9]{2})/', $expirationDate, $matches)) {

2

試試這將有助於同時檢查日期格式,檢查日期是否有效或無效:

if (!preg_match('/^([0-9]{4})\-([0-9]{2})$/', $expirationDate, $matches)) { 
    throw new Services_Payment_Exception('Card expiration date is wrong format'); 

}else if (!strtotime($expirationDate)){ 
    throw new Services_Payment_Exception('Card expiration date is invalid'); 
}