只需输入您想转换为秒的英文时间(例如,“1小时30分钟”),它就会转换为秒的整数(例如,5400)。感谢Baylor Rae。
function time2seconds($time) {
preg_match_all('/(\d+ [a-z]+)/', $time, $matches);
$matches = $matches[0];
$formats = array();
foreach ($matches as $format) {
preg_match('/(\d+)\s?([a-z]+)/', $format, $f);
$time = $f[1];
$type = $f[2];
$formats[$type] = $time;
}
$output = array(
'years' => 0,
'months' => 0,
'days' => 0,
'hours' => 0,
'minutes' => 0,
'seconds' => 0
);
foreach ($formats as $format => $time) {
if( $time == 0 )
continue;
switch ($format) {
case 'year' :
case 'years' :
$output['years'] = $time * 12 * 30 * 24 * 60 * 60;
break;
case 'month' :
case 'months' :
$output['months'] = $time * 30 * 24 * 60 * 60;
break;
case 'day' :
case 'days' :
$output['days'] = $time * 24 * 60 * 60;
break;
case 'hour' :
case 'hours' :
$output['hours'] = $time * 60 * 60;
break;
case 'minute' :
case 'minutes' :
$output['minutes'] = $time * 60;
break;
case 'second' :
case 'seconds' :
$output['seconds'] = $time;
break;
}
}
return $output['years'] + $output['months'] + $output['days'] + $output['hours'] + $output['minutes'] + $output['seconds'];
}
简单用法
表单提交“time”
<form method="post">
<label for="time">Time</label><br />
<input type="text" name="time" id="time" size="50" value="<?php echo (isset($_POST['time'])) ? $_POST['time'] : '1 hour 30 minutes' ?>" />
<button name="submit">Test!</button>
</form>
如果设置了“time”,则使用该函数并回显返回值
if (isset($_POST)) {
echo time2seconds($_POST['time']);
}