[英]Creating a function in php that checks that get value is in the order dd/mm/yyy
I'm currently building a room booking system and was wondering how to check if the user has entered a date (get value) in the correct UK format of dd/mm/yyyy. 我正在建立一个房间预订系统,并想知道如何检查用户是否输入了正确的英国格式dd / mm / yyyy的日期(获取值)。
$uk_date = $_GET["date"];
For example to avoid a situation where the user types in 12/2012 or 2012 or uses the incorrect separators. 例如,避免用户在12/2012或2012中键入或使用不正确的分隔符的情况。
Thanks in advance! 提前致谢!
The best would be DateTime::createFromFormat
: 最好的是
DateTime::createFromFormat
:
$date = DateTime::createFromFormat('d/m/Y', $uk_date);
$errors = DateTime::getLastErrors();
if($errors['warning_count'] || $errors['error_count']) {
// something went wrong, you can look into $errors to see what exactly
}
If the parsing is successful then you have in your hands a DateTime
object that provides lots of useful functions. 如果解析成功,那么您将拥有一个提供许多有用功能的
DateTime
对象。 One of the most important is DateTime::format
which will let you get data out of the object, eg: 其中最重要的是
DateTime::format
,它可以让你从对象中获取数据,例如:
$year = $date->format('Y');
Use a regex code like this: 使用这样的正则表达式代码:
$str = '12/12/2012';
$regex = '#^\d{1,2}([/-])\d{1,2}\1\d{4}$#';
if (preg_match($regex, $str, $m))
echo "valid date\n";
Try this function: 试试这个功能:
public static function CheckValidDate($sDate) {
$sDate = str_replace('/', '-', $sDate);
preg_match('/^(\d{2})-(\d{2})-(\d{4})$/', $sDate, $xadBits);
if ($xadBits)
return checkdate($xadBits[2], $xadBits[1], $xadBits[3]);
else
return false;
}
Visit the reference: http://php.net/manual/en/function.checkdate.php 访问参考: http : //php.net/manual/en/function.checkdate.php
Thanks for the comment @SalmanA 感谢@SalmanA的评论
Try this regular expression: 试试这个正则表达式:
$pattern = '|^[\d]{,2}/[\d]{,2}/[\d]{,4}$|is';
if (preg_match($pattern, $date, $match)) {
echo 'ok!';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.