I have a regex to reformat a date from "dd/mm/yyyy HH:ii:ss" to YYYY-MM-DD HH:II:SS which is fine, but I would also use the same for validating date only (when no hours are provided).
Maybe there is a way to give default value to the replacement but I didn't found it.
$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"
You can use preg_replace_callback
and provide a custom callback method to perform the replacement. Inside you're callback, you can apply your default values:
$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"
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments