[英]PHP regex output converting
我想将12h 34m 45s的输出转换为12:34:45
它也应该是可能的,如果其中一个返回空,将忽略它。 所以34m 45s应该是00:34:45并且当然单个数字应该可能像1h 4m 1s和组合关闭单个和两个数字,如12h 4m 12s等等。
有人可以帮忙吗?
这是实际的代码
$van = $_POST['gespreksduur_van']; $tot = $_POST['gespreksduur_tot']; $regex = '/(\\d\\d?h ?)?(\\d\\d?m ?)?(\\d\\d?s)?/';
if(preg_match($regex, $van, $match) AND preg_match($regex, $tot, $matches))
{
for ($n = 1; $n <= 3; ++$n) { if (!array_key_exists($n, $match)) $match[$n] = 0; }
for ($i = 1; $i <= 3; ++$i) { if (!array_key_exists($i, $matches)) $matches[$i] = 0; }
$van = printf("%02d:%02d:%02d", $matches[1], $matches[2], $matches[3]);
$tot = printf("%02d:%02d:%02d", $match[1], $match[2], $match[3]);
print($van);
print($tot);
$data['gespreksduurvan'] = htmlspecialchars($van);
$data['gespreksduurtot'] = htmlspecialchars($tot);
$smarty->assign('gsv',$data['gespreksduurvan']);
$smarty->assign('gst',$data['gespreksduurtot']);
}
您可以使用正则表达式来提取组件,然后使用printf()
来按照您的喜好格式化组件:
$time = "1h 45m";
preg_match("/(\d\d?h ?)?(\d\d?m ?)?(\d\d?s)?/", $time, $matches);
for ($i = 1; $i <= 3; ++$i) { if (!array_key_exists($i, $matches)) $matches[$i] = 0; }
printf("%02d:%02d:%02d", $matches[1], $matches[2], $matches[3]);
正则表达式允许可选组件。 for循环只是填充任何缺少的键,默认值为零(以防止在秒或两个分钟/秒丢失时未定义的键错误)。 printf始终使用两个零打印所有组件。
如果要使用正则表达式,可以使用preg_replace_callback
<?php
function callback($matches)
{
var_dump($matches);
if ($matches[2] == "") $matches[2] = "00";
if ($matches[4] == "") $matches[4] = "00";
if ($matches[6] == "") $matches[6] = "00";
return $matches[2] . ":" . $matches[4] . ":" . $matches[6];
}
$str = "12h 34m 45s";
$str = preg_replace_callback("`(([0-2]?[0-9])h )?(([0-5]?[0-9])m )?(([0-5]?[0-9])s)?`", "callback", $str, 1);
echo $str;
这就是你如何在没有正则表达式的情况下做到这一点
// function for your purpose
function to_time($str){
$time_arr = explode(' ', $str);
$time_h = '00';
$time_m = '00';
$time_s = '00';
foreach($time_arr as $v){
switch(substr($v, -1)){
case 'h': $time_h = intval($v); break;
case 'm': $time_m = intval($v); break;
case 's': $time_s = intval($v); break;
}
}
return $time_h . ':' . $time_m . ':' . $time_s;
}
//test array
$time[] = '1h 45s';
$time[] = '12h 35m 45s';
$time[] = '1m 45s';
// output
foreach($time as $t)
var_dump(to_time($t));
这输出
string '1:00:45' (length=7)
string '12:35:45' (length=8)
string '00:1:45' (length=7)
$string = "12h 34m 45s";
$string = str_replace(array("h","m","s"), array(":",":",""), str_replace(" ", "", $string));
echo $string;
像这样的东西?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.