什么是MM / DD / YYYY正则表达式,如何在php中使用它? [英] What is the MM/DD/YYYY regular expression and how do I use it in php?

查看:160
本文介绍了什么是MM / DD / YYYY正则表达式,如何在php中使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我的代码:

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

当我运行这个,它仍然回显这个日期格式不正确当应该说相反的时候。如何将这个正则表达式设置为php?

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?

推荐答案

问题是一个分隔符和转义字符(正如其他人所提到的那样) )。这将工作:

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.

为了进一步,这种模式不会正确地提取一年。就在这个世纪。您需要将其更改为 /(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)$ /

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

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

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:

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

这篇关于什么是MM / DD / YYYY正则表达式,如何在php中使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆