如何使用preg_replace将一小时添加到时间值? [英] How to use preg_replace to add one hour to a time value?
问题描述
我有一个页面显示时间如下: 10:00 am
。我需要花些时间,给他们增加一个小时。我提出了一个正则表达式来处理自己找到时间,我只是不知道下一步该怎么做。这是我的正则表达式: ^(1 [012] | [1-9]):([0-5] [0-9])(?i)(am | pm)^
。
任何帮助将不胜感激。 -Austin
你可以这样做,不需要任何正则表达式:
$ time = '10:00am';
list($ hour,$ min)= explode(':',$ time);
echo date('h:ia',mktime((int)$ hour + 1,(int)$ min));
转换为 int
am
,以便分钟部分可用于 mktime
。
如果您需要使用正则表达式(例如,您正在搜索更大字符串内的时间),则可以使用以下代码:
的preg_match('〜^(1 [012] | [1-9]):([0-5] [0-9])(ⅰ)(AM | PM) ^〜',$ str,$ matches);
echo date('h:ia',mktime($ match [1] + 1,$ match [2]));
而且,如果您需要在原始字符串内替换那些时间,您可以使用 preg_replace_callback
:
$ time = preg_replace_callback('〜( 1 [012] | [1-9]):([0-5] [0-9])(?i)(am | pm)〜',
function($ matches){
返回日期('h:ia',mktime($ matches [1] + 1,$ matches [2]));
},
$ time);
适用于PHP 5.2及更高版本的版本:
<$ ([0-5] [0-9])(?i)(am | pm(p))。 )〜',
create_function(
'$ matches',
'return date(\'h:ia\',mktime($ matches [1] + 1,$ matches [ 2]));'
},
$ time);
I have a page that shows times on it like this: 10:00am
. I need to take those times, and add one hour 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)^
.
Any help would be greatly appreciated. -Austin
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);
这篇关于如何使用preg_replace将一小时添加到时间值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!