1

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
  • How are you receiving the formats, 138 or 1h 38min? Commented Feb 24, 2010 at 2:07
  • sometimes it comes like 1h 38 min and sometimes its like 2h 20 min, thing is like 1 hours or 2 hours Commented Feb 24, 2010 at 2:23

3 Answers 3

2

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' */
Sign up to request clarification or add additional context in comments.

Comments

0
$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";
}

Comments

0
$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";
}

1 Comment

preg replace gives error Parse error: syntax error, unexpected T_FUNCTION

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.