What is the MM/DD/YYYY regular expression and how do I use it in php?

后端 未结 9 969
清歌不尽
清歌不尽 2020-12-03 05:11

I found the regular expression for MM/DD/YYYY at http://www.regular-expressions.info/regexbuddy/datemmddyyyy.html but I don\'t think I am using it correctly.

Here\'s

9条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 05:23

    To use this regex to validate dates in PHP code, you need to correctly format it as a string with additional regex delimiters as the PHP preg functions require. You also need to add anchors to force the regex to match the entire string (or else fail to match):

    $date_regex = '%\A(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d\z%'; 
    
    $test_date = '03/22/2010'; 
    if(preg_match($date_regex, $test_date)) { 
      echo 'this date is formatted correctly';   
    } else { 
      echo 'this date is not formatted correctly';   
    } 
    

    Of course, a library call would be better in this situation. The regex allows invalid dates such as February 31st.

    The regex can be useful if you want to scan a string for dates. In that case you don't need the anchors. You may still need an extra check to exclude invalid dates. That depends on whether your input is know to contain only valid dates or not.

提交回复
热议问题