How to check the data format in PHP

前端 未结 6 1797
忘掉有多难
忘掉有多难 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:15

    Use a regular expression, as others have suggested. The ones posted before will accept invalid dates such as 99/99/9999 however. Here's an improved regex (lifed from here)

    $date_regex = '!^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$!';
    if (preg_match($date_regex, $date)) {
       // do something
    }
    

    It will only take valid dates and it will also accept different separators (such as 05.20.2002 and 05-02-2002).

    If you ask me it's bad user experience to force them to enter a particular format. YOU can handle different formats using strtotime().

提交回复
热议问题