PHP编程新手。正在尝试验证日期/时间的输入格式。用户输入如下: 2012年11月27日下午6点:2012-11月27日|下午6点。
我真的不知道该从哪里开始。有什么建议吗?谢谢。
发布于 2012-11-08 23:54:14
查看date_parse_from_format文档的here和常规日期格式的here。试一试:
<?php
$date = "2012-nov-27|6pm";
print_r(date_parse_from_format("Y-M-d|ga", $date));
?>发布于 2012-11-08 23:53:00
您可以使用checkdate
if(checkdate($month, $day, $year)){
echo 'Valid date!';
}或者,您可以转换用户使用strtotime()输入的任何内容。如果strtotime不能确定日期,它将返回bool false。
if(strtotime($dateEntered) !== false){
echo 'Valid date!';
}发布于 2012-11-08 23:53:47
如果只想检查格式,可以使用正则表达式:
$months = 'jan|feb|mar|apr|may|jun|jul|aug|sep|okt|nov|dec';
$pattern = '/([0-9]{4})-('.$months.')-([0-9]{2})\\|([0-9]?[0-9])(am|pm)/';
preg_match($pattern, $input, $matches);
var_dump($matches);如果你真的想检查某个特定的日期/时间是否存在,事情就会变得更加复杂。我可能错了,但我不认为使用PHP日期函数可以做到这一点,因为它们对输入错误的容忍度很高。也许有一个库可以做到这一点。
https://stackoverflow.com/questions/13292476
复制相似问题