我想将我的时间期限从1h 20m 53s转换成01:20:53格式。我的时间期限可能只有20m 53s、25m或1h或23s。我需要把它转换成00:00:00的时间格式。
发布于 2014-04-08 11:06:53
您可以使用^(?:(?<hours>\d+)h\s*)?(?:(?<minutes>\d+)m\s*)?(?:(?<seconds>\d+)s\s*)?$和sprintf的正则表达式来确保零被加在前面:
<?php
function translateTime($timeString) {
if (preg_match('/^(?:(?<hours>\d+)h\s*)?(?:(?<minutes>\d+)m\s*)?(?:(?<seconds>\d+)s\s*)?$/', $timeString, $matches)) {
return sprintf(
'%02s:%02s:%02s',
(!empty($matches['hours']) ? $matches['hours'] : '00'),
(!empty($matches['minutes']) ? $matches['minutes'] : '00'),
(!empty($matches['seconds']) ? $matches['seconds'] : '00')
);
}
return '00:00:00';
}
var_dump( translateTime('1h 20m 53s') ); //string(8) "01:20:53"
var_dump( translateTime('20m 53s') ); //string(8) "00:20:53"
var_dump( translateTime('53s') ); //string(8) "00:00:53"
var_dump( translateTime('1h 30s') ); //string(8) "01:00:30"
var_dump( translateTime('2h 3m') ); //string(8) "02:03:00"虽然看起来很可怕,但regex只是一群命名的捕获组:

\s是空白字符(空格、制表符、\r、\n、\f)
\d是一个数字(0、1、2、3、4、5、6、7、8、9)
发布于 2014-04-08 11:07:48
首先,使字符串与php DateTime对象兼容。
$time = preg_split( "/(h|m|s)/i", " 1H 20m 53s " , null, PREG_SPLIT_DELIM_CAPTURE);
$h = 0;
$m = 0;
$s = 0;
$count = count($time);
if ($count == 7)
{
${strtolower($time[1])} = $time[0];
${strtolower($time[3])} = $time[2];
${strtolower($time[5])} = $time[4];
}
else if ($count == 5)
{
${strtolower($time[1])} = $time[0];
${strtolower($time[3])} = $time[2];
}
else if ($count == 3)
{
${strtolower($time[1])} = $time[0];
}
$date = new \DateTime();
$date->setTime($h, $m, $s);
echo $date->format('H:i:s');您现在可以以php DateTime支持的任何格式发布它。
https://stackoverflow.com/questions/22934814
复制相似问题