How to check the data format in PHP

前端 未结 6 1798
忘掉有多难
忘掉有多难 2021-01-21 04:07

I am trying to check a date format to see if I can check the data variable has certain format like MM-DD-YYYY. if not, then exit(). I am not sure how to check the format and wou

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-21 04:30

    If I understand you correctly, you want to check a string to make sure it follows the MM-DD-YYYY pattern?

    If so, I would suggest two checks: one to make sure it follows the general pattern of digits, and another to check that the months are first and days are second.

    function checkDate( $date )
    {
    
        if (preg_match("/[0|1][0-9]/[0-9][1-9]/[0-9]{4}/",$date)
        {
            if (substr($date,0,2)<=12 && substr($date,3,2)<=31)
            {
                 return true;
            }
        }
        return false
    
    }
    

    Update: Added an additional check on the days to make sure it is valid, based on NullUser's comment

提交回复
热议问题