我有一个正则表达式,将日期从“dd / mm / yyyy HH:ii:ss”重新格式化为YYYY-MM-DD HH:II:SS很好,但我也会使用同样的日期验证日期(当没有提供时间时)。
也许有一种方法可以为替换提供默认值,但我没有找到它。
$regex = '#^(\d{2})/(\d{2})/(\d{4})(?: (\d{2}):(\d{2})(?::(\d{2}))?)?$#';
$replace = '$3-$2-$1 $4:$5:00';
$str = '07/11/2013 20:30';
$val = preg_replace($regex, $replace, $str);
echo $val; // "2013-11-07 20:30:00"
$str = '07/11/2013';
$val = preg_replace($regex, $replace, $str);
echo $val; // "2013-11-07 ::00"
答案 0 :(得分:2)
您可以使用preg_replace_callback
并提供自定义回调方法来执行替换。在你回调中,你可以应用你的默认值:
$regex = '#^(\d{2})/(\d{2})/(\d{4})(?: (\d{2}):(\d{2})(?::(\d{2}))?)?$#';
$replace = function ($m) {
if (!$m[4]) $m[4] = '00';
if (!$m[5]) $m[5] = '00';
return "$m[3]-$m[2]-$m[1] $m[4]:$m[5]:00";
};
$str = '07/11/2013 20:30';
$val = preg_replace_callback($regex, $replace, $str);
echo $val; // "2013-11-07 20:30:00"
$str = '07/11/2013';
$val = preg_replace_callback($regex, $replace, $str);
echo $val; // "2013-11-07 00:00:00"
答案 1 :(得分:0)
要验证日期和时间,请尝试以下操作:
$regex = '(\d{2})/(\d{2})/(\d{4}) (\d{2}):(\d{2}):(\d{2})';