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

zec*_*ude 22 php regex date

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

这是我的代码:

$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';  
}
Run Code Online (Sandbox Code Playgroud)

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

Jer*_*gan 45

问题是分界符和转义字符之一(正如其他人提到的那样).这将有效:

$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';
}
Run Code Online (Sandbox Code Playgroud)

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

更进一步,这种模式将无法正确地提取年份......仅仅是一个世纪./(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.]((?:19|20)\d\d)/如果你想确保整个字符串匹配(而不是某些子集)你需要更喜欢的东西,你需要将它改为和(如Jan指出的那样)/^(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.]((?:19|20)\d\d)$/.


正如其他人所提到的,如果你只是试图让日期结束,那么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'];    
Run Code Online (Sandbox Code Playgroud)


DCD*_*DCD 5

最好使用strtotime()将几乎任何人类可读的日期格式转换为unix时间戳.- http://php.net/manual/en/function.strtotime.php


fux*_*xia 5

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

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


aza*_*aim 5

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

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

或者如果要花哨:

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

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

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

([0-9]|0[1-9]|1[012])
Run Code Online (Sandbox Code Playgroud)

说明:
[0-9] - 0 和 9 之间的单个数字

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

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