views:

102

answers:

3

i m just wondering if we can do this with preg replace

like if there's time like

1h 38 min

can change to

98 mins

2h 20 min

can change to

140 mins

or just suggest me any other random function to this is simpler way

thanks

+2  A: 

This simple function should do the trick. It does no verification on the string format, though.

function reformat_time_string($timestr) {
    $vals = sscanf($timestr, "%dh %dm");
    $total_min = ($vals[0] * 60) + $vals[1];
    return "$total_min mins";
}

$timestr = "2h 15m";
echo reformat_time_string($timestr); /* echoes '135 mins' */
gnud
A: 
$pattern = '!(\d+)\s*h\s*(\d+)\s*min!';
foreach( array('1h 38 min', '2h 20 min') as $input) {
  echo preg_replace_callback($pattern, function($x) { return ($x[1]*60+$x[2]).' minutes'; }, $input), "\n";
}

prints

98 minutes
140 minutes

for php versions prior to 5.3 you'd have to use

function foo($x) {
  return ($x[1]*60+$x[2]).' minutes';
}
$pattern = '!(\d+)\s*h\s*(\d+)\s*min!';
foreach( array('1h 38 min', '2h 20 min') as $input) {
  echo preg_replace_callback($pattern, 'foo', $input), "\n";
}
VolkerK
preg replace gives error Parse error: syntax error, unexpected T_FUNCTION
Jegeg
Your php version is < 5.3.
VolkerK
A: 
$str="1h 38 min";
$s = explode(" ",$str);
if ( strpos ( $s[0] ,"h" ) !==FALSE) {
    $hr=str_replace("h","",$s[0]);
    print ($hr*60) + $s[1]."\n";
}
ghostdog74
works like charm :D
Jegeg