How to check the data format in PHP

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

    If you are trying to do this to limit user's input, you can always use strtotime() on the users input and convert it to a unix timestamp then use the date() function to display it how you want to.

    If you really want to determine if it is in a certain format, or only require a certain format, a preg_match() with a regular expression will be of assistance, I believe on that page they have examples of parsing dates. If not it would be something like this:

    if (preg_match('~[0-9]{2}-[0-9]{2}-[0-9]{4}~', $dateStr)) { echo 'Correct format'; }

    The obvious flaw with that is the date may pass the format test, but may not be a valid date. In my opinion, accept any date in the user input and use the strtotime / date to get it to the format you want.

提交回复
热议问题