Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何检查字符串';PHP中的日期格式?_Php_Regex_Preg Match - Fatal编程技术网

如何检查字符串';PHP中的日期格式?

如何检查字符串';PHP中的日期格式?,php,regex,preg-match,Php,Regex,Preg Match,我想检查字符串是否具有此时间格式: Y-m-d H:i:s 如果没有,则执行一些代码,例如 if here will be condition do { this } else do { this } 如何在PHP中实现此条件?答案可能包括。我建议您阅读此文档,如果您仍然有问题,请返回此处。您可以强制执行以下操作: date('Y-m-d H:i:s',strtotime($str)); preg_match是您需要的,特别是: if(preg_match('/\d{4}-\d{2}-\d

我想检查字符串是否具有此时间格式:

Y-m-d H:i:s
如果没有,则执行一些代码,例如

if here will be condition do { this }
else do { this }

如何在PHP中实现此条件?

答案可能包括。我建议您阅读此文档,如果您仍然有问题,请返回此处。

您可以强制执行以下操作:

date('Y-m-d H:i:s',strtotime($str));

preg_match
是您需要的,特别是:

if(preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/',$date)){
   //dothis
}else{
   //dothat
}
如果您真的只想要格式正确的日期,那么

/\d{4}-[01]\d-[0-3]\d [0-2]\d:[0-5]\d:[0-5]\d/

你没有。无法判断它是
Y-m-d
还是
Y-d-m
,甚至是
Y-d-d
vs
Y-m-m
。什么是
2012-05-12
?5月12日还是12月5日

但是,如果你对此感到满意,你可以:

// convert it through strtotime to get the date and back.
if( $dt == date('Y-m-d H:i:s',strtotime($dt)) )
{
    // date is in fact in one of the above formats
}
else
{
    // date is something else.
}
尽管您可能想看看
preg_match('/\d{4}-\d{2}-\d{2}-\d{2}:\d{2}:\d{2}/',$date)
在这方面是否更快。我还没有测试过

if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $yourdate)) {
   // it's in the right format ...
} else {
  // not the right format ...
}
请注意,这只检查日期字符串是否像由冒号和破折号分隔的一组数字。它不会在一段时间内(99点?)检查诸如“2011-02-31”(2月31日)或“99:99:99”之类的奇怪现象。

来自

这里有一个很酷的函数来验证mysql日期时间:

<?php
function isValidDateTime($dateTime)
{
    if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $dateTime, $matches)) {
        if (checkdate($matches[2], $matches[3], $matches[1])) {
            return true;
        }
    }

    return false;
}
?>

如何在PHP中检查字符串的日期格式?

 if (DateTime::createFromFormat('Y-m-d G:i:s', $myString) !== FALSE) {
 echo 'true';
}                                                               

这也是输入还是什么?每个人都会使用这个吗?我这样问是因为为什么不创建日期呢?然后它可以是您想要的任何格式。否则,正如您已经猜到的,正则表达式是最好的方法。尽管如此,它仍然可能是无效的。闰年之类的。在本例中,我将重复一句名言:有些人在遇到问题时,会想“我知道,我会使用正则表达式。”现在他们有两个问题-Jamie Zawinski,我觉得这就是其中之一。@Matt:regex标记是我添加的,不是kaspernov添加的
Y-m-m
2012-05-12
。。。2012年5月12日。比我书中的正则表达式优雅得多。谢谢,这解决了我的问题,而不必再添加其他问题。为什么列表中的这个不在较高的位置?失败的案例$myString='19-12-09 12:31:30';if(DateTime::createFromFormat('Y-m-dg:i:s',$myString)!==FALSE){echo'true';}