How to use preg_replace to add one hour to a time value?
I have a page that shows times on it like this: 10:00am
. I need to take those times, and add one 开发者_如何学Pythonhour to them. I have come up with a regular expression to deal with finding the times themselves, I just don't know what to do next. This is the regex I have: ^(1[012]|[1-9]):([0-5][0-9])(?i)(am|pm)^
.
You can also use this one-liner: echo date("h:ia", strtotime("10:43am +1 hour"));
, replace 10:43 with an interpolated variable and make sure it's parsable by strtotime()
(your example format is).
You can do something like this, don't need any regexes:
$time = '10:00am';
list($hour, $min) = explode(':', $time);
echo date('h:ia', mktime((int)$hour + 1, (int)$min));
Casting to int
gets rid of the trailing am
so that the minutes part can be used in mktime
.
If you need to use the regex (for example, you are searching for times inside a larger string), you can use this:
preg_match('~^(1[012]|[1-9]):([0-5][0-9])(?i)(am|pm)^~', $str, $matches);
echo date('h:ia', mktime($match[1] + 1, $match[2]));
And, if you need to replace those times inside the original string, you can use preg_replace_callback
:
$time = preg_replace_callback('~(1[012]|[1-9]):([0-5][0-9])(?i)(am|pm)~',
function($matches) {
return date('h:ia', mktime($matches[1] + 1, $matches[2]));
},
$time);
Version for PHP 5.2 and older:
$time = preg_replace_callback('~(1[012]|[1-9]):([0-5][0-9])(?i)(am|pm)~',
create_function(
'$matches',
'return date(\'h:ia\', mktime($matches[1] + 1, $matches[2]));'
},
$time);
Parse the time to "part" variables, perform your modifications, and put the parts back into a new string.
For example:
$time = '10:00am';
$time = substr($time, 0, 5);
$ampm = substr($time, 6);
list($hours, $minutes) = explode(':', $time);
// do your thing
$newtime = sprintf('%02d:%02d%s', $hours, $minutes, $ampm);
精彩评论