PHP regex output converting
I want to turn a output like 12h 34m 45s to 12:34:45
also it should be pos开发者_C百科sible if one o these is returned empty is will ignore it. So 34m 45s should be 00:34:45 and off course single digits should bee possible like 1h 4m 1s and a combo off single and double digits like 12h 4m 12s and so on.
Can someone please help ?
This is the actual code
$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']);
}
You can use a regex to extract the components, and then a printf()
to format the components how you like:
$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]);
The regex allows optional components. The for loop there just fills any missing keys with a default value of zero (to prevent undefined key errors when seconds, or both minutes/seconds are missing). The printf always prints all components with two zeros.
If you want to use regex, you can use 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;
this is how you can do this without regex
// 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));
This outputs
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;
Something like this?
精彩评论