什么是 MM/DD/YYYY 正则表达式以及如何在 php 中使用它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2520633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:48:21  来源:igfitidea点击:

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

phpregexdate

提问by zeckdude

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

我在http://www.regular-expressions.info/regexbuddy/datemmddyyyy.html找到了 MM/DD/YYYY 的正则表达式,但我认为我没有正确使用它。

Here's my code:

这是我的代码:

$date_regex = '(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d';

$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';  
}

When I run this, it still echoes 'this date is not formatted correctly', when it should be saying the opposite. How do I set this regular expression up in php?

当我运行它时,它仍然回响“此日期格式不正确”,而应该说相反。如何在 php 中设置这个正则表达式?

回答by Jeremy Logan

The problem is one of delimeters and escaped characters (as others have mentioned). This will work:

问题是分隔符和转义字符之一(正如其他人所提到的)。这将起作用:

$date_regex = '/(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d/';

$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';
}

Note that I added a forward-slash to the beginning and ending of the expression and escapped (with a back-slash) the forward-slashes in the pattern.

请注意,我在表达式的开头和结尾添加了一个正斜杠,并将模式中的正斜杠转义(使用反斜杠)。

To take it one step further, this pattern won't properly extract the year... just the century. You'd need to change it to /(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.]((?:19|20)\d\d)/and (as Jan pointed out below) if you want to make sure the whole string matches (instead of some subset) you'll want to go with something more like /^(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.]((?:19|20)\d\d)$/.

更进一步,这种模式不能正确提取年份……只是世纪。/(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.]((?:19|20)\d\d)/如果您想确保整个字符串匹配(而不是某些子集),您需要将其更改为and(正如 Jan 在下面指出的那样),您需要使用更像/^(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.]((?:19|20)\d\d)$/.



As others have mentioned, strtotime()might be a better option if you're just trying to get the date out. It can parse almost any commonly used format and it will give you a unix timestamp. You can use it like this:

正如其他人所提到的,如果您只是想确定日期,strtotime()可能是更好的选择。它可以解析几乎任何常用的格式,并且会给你一个 unix 时间戳。你可以这样使用它:

$test_date = '03/22/2010';

// get the unix timestamp for the date
$timestamp = strtorime($test_date);

// now you can get the date fields back out with one of the normal date/time functions. example:
$date_array = getdate($timestamp);
echo 'the month is: ' . $date_array['month'];    

回答by DCD

Its probably better to use strtotime() which will convert nearly any human-readable date format to a unix timestamp. - http://php.net/manual/en/function.strtotime.php

使用 strtotime() 可能会更好,它将几乎所有人类可读的日期格式转换为 unix 时间戳。- http://php.net/manual/en/function.strtotime.php

回答by fuxia

You need correct delimitersaround the pattern.

您需要在模式周围使用正确的分隔符

$date_regex = '~(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d~';

回答by azakgaim

Regex of the author of the question is almost correct. Date is not validated because a pattern should be:

问题作者的正则表达式几乎是正确的。日期未验证,因为模式应该是:

  pattern="^(0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])[/](19|20)\d\d$"

or if to be fancy:

或者如果要花哨:

  pattern="^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$"

Please note that this pattern checks only for a format of a date and max/min values for individual date elements. That means a user's entry should be checked for validity of date in JavaScript function and/or a Server (e.g February 29 should not be allowed if a year is not a leap one).

请注意,此模式仅检查日期格式和单个日期元素的最大值/最小值。这意味着应该检查用户输入的 JavaScript 函数和/或服务器中日期的有效性(例如,如果一年不是闰年,则不应允许 2 月 29 日)。

As a side note, if you would like to allow a single digit (let's say for a month), change a month part to

作为旁注,如果您想允许一个数字(假设一个月),请将月份部分更改为

([0-9]|0[1-9]|1[012])

Explanation:
[0-9] - single digit between 0 and 9
or
0[1-9] - two digits between 01 and 09
or
1[012] - two digits limited to 10, 11, 12

说明:
[0-9] - 0 和 9 之间的一位数

0[1-9] - 01 和 09 之间的两位数

1[012] - 两位数限制为 10、11、12

回答by ghostdog74

you can use the checkdate()function as well. No need regex.

您也可以使用checkdate()函数。不需要正则表达式。

$str="03/22/2010";
list($mth,$day,$yr)=explode("/",$str);
var_dump(checkdate($mth,$day,$yr));

回答by Jan Goyvaerts

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):

要使用此正则表达式来验证 PHP 代码中的日期,您需要按照 PHP preg 函数的要求将其正确格式化为带有附加正则表达式分隔符的字符串。您还需要添加锚点以强制正则表达式匹配整个字符串(否则无法匹配):

$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.

当然,在这种情况下,调用库会更好。正则表达式允许无效日期,例如 2 月 31 日。

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.

如果您想扫描字符串中的日期,正则表达式会很有用。在这种情况下,您不需要锚点。您可能仍需要额外检查以排除无效日期。这取决于您的输入是否知道仅包含有效日期。

回答by Jan Goyvaerts

This checks valid dates from MM/DD/1960to MM/DD/2014

这将检查有效日期从MM/DD/1960MM/DD/2014

Also accepts dates like M/D/YYYYand 0M/0D/YYYY

也接受像M/D/YYYY和这样的日期0M/0D/YYYY

^(?:[1-9]|0[1-9]|1[0-2])/(?:[0-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])/(?:20[6-9][0-9]|20[0-1][0-4])$

回答by Yoga Gowda

String timeStamp = "03/11/2018 17:51:45";

字符串时间戳 = "03/11/2018 17:51:45";

private static Pattern TIMESTAMP_PATTERN = Pattern.compile("(0?[1-9]|1[012])/(0?[1-9]|[1-2][0-9]|3[0-1])/" + "([1-9][0-9]{3}) ([0-1]?[0-9]|2[0-3]):([0-5]?[0-9]):([0-5]?[0-9])");

私有静态模式 TIMESTAMP_PATTERN = Pattern.compile("(0?[1-9]|1[012])/(0?[1-9]|[1-2][0-9]|3[0-1 ])/" + "([1-9][0-9]{3}) ([0-1]?[0-9]|2[0-3]):([0-5]?[ 0-9]):([0-5]?[0-9])");

private static boolean isTimeStampValid(String timeStamp) {
        boolean isFeb = timeStamp.split("/")[0].matches("(0?[2])");
        if (isFeb) {
            boolean isValidFebDate = timeStamp.split("/")[1].matches("(0?[1-9]|1[1-9]|2[0-8])");
            if (!isValidFebDate) return false;
        }
        return TIMESTAMP_PATTERN.matcher(timeStamp).matches();
    }

回答by Amy B

Your regex needs delimiters:

您的正则表达式需要分隔符:

/(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d/

/(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d/