php preg_match a date format "yyyy-MM"


php preg_match a date format "yyyy-MM"

我正在尝试使用preg_match中修改的preg格式:检查生日格式(dd/mm/yyyy)以匹配信用卡到期日期(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)

锚定正则表达式:

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

您的regexp没有达到预期效果,因为它与"20111-02"的"0111-02"子字符串匹配。

^$与输入字符串中的特定位置匹配:^与字符串的开头匹配,$与结尾匹配。

还要注意,不需要转义连字符,因为它在[]中只有一个特殊的功能。

使用^$锚点:

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部分。

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

更改:

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

至:

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

所以它只检查整个字符串。

试试这个:if (!preg_match('/^([0-9]{4})'-([0-9]{2})/', $expirationDate, $matches)) {

试试这个,它将有助于检查日期格式和日期是否有效:

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');
}