PHP Regex to check date is in YYYY-MM-DD format

前端 未结 23 1564
终归单人心
终归单人心 2020-11-27 10:05

I\'m trying to check that dates entered by end users are in the YYYY-MM-DD. Regex has never been my strong point, I keep getting a false return value for the preg_match() I

23条回答
  •  鱼传尺愫
    2020-11-27 10:26

    It all depends on how strict you want this function to be. For instance, if you don't want to allow months above 12 and days above 31 (not depending on the month, that would require writing date-logic), it could become pretty complicated:

    function checkDate($date)
    {
      $regex = '/^' . 
        '(' .
    
        // Allows years 0000-9999
        '(?:[0-9]{4})' .
        '\-' .
    
        // Allows 01-12
        '(?:' .
        '(?:01)|(?:02)|(?:03)|(?:04)|(?:05)|(?:06)|(?:07)|(?:08)|(?:09)|(?:10)|' .
        '(?:11)|(?:12)' .
        ')' .
        '\-' .
    
        // Allows 01-31
        '(?:' .
        '(?:01)|(?:02)|(?:03)|(?:04)|(?:05)|(?:06)|(?:07)|(?:08)|(?:09)|(?:10)|' .
        '(?:11)|(?:12)|(?:13)|(?:14)|(?:15)|(?:16)|(?:17)|(?:18)|(?:19)|(?:20)|' .
        '(?:21)|(?:22)|(?:23)|(?:24)|(?:25)|(?:26)|(?:27)|(?:28)|(?:29)|(?:30)|' .
        '(?:31)' .
        ')' .
    
        '$/';
    
      if ( preg_match($regex, $date) ) {
        return true;
      }
    
      return false;
    }
    
    $result = checkDate('2012-09-12');
    

    Personally I'd just go for: /^([0-9]{4}\-([0-9]{2}\-[0-9]{2})$/

提交回复
热议问题