Link to home
Start Free TrialLog in
Avatar of hankknight
hankknightFlag for Canada

asked on

Convert phrase to kph from mph

I want a function to convert miles per hour to kilometers per hour within a phrase.

KPH may be found by dividing MPH by 0.621.

100 mph = 161 kph.

The challenge is finding the values within my text.

///////////////////////////
echo mi2km("Wind: South at 100 mph");  
      /// Wind: South at 161 kph

echo mi2km("Wind: N at 33 mph");
      /// Wind: N at 53 mph
ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The best way is probably to use regex to locate the number. I can't think of the regex that would do this off the top of my head, but you can use php's array functions for a simular result.

The bonus of the following say is that as long as the string ends with *** mph it will always work, no matter what is in front of it.
function mi2km($distance) {
  $distance_array = explode(" ",$distance);
  $distance_array = array_reverse($distance_array);
  $distance_array[1] = $distance_array[1] * 1.61;
  return impode(" ", array_reverse($distance_array));
}

Open in new window

here is my version
function mi2km($mystring) {
preg_match('/([^ ]*) (?=mph)/i', $mystring, $matches);
$kph=intval($matches[0]/0.621);
return  preg_replace('/([^ ]*) mph/i', $kph . " kph", $mystring);
}
echo mi2km("Wind: N at 33 mph"); 
echo mi2km("Wind: South at 100 mph");

Open in new window

Could have been so much easier:

preg_replace('/(\d+) mph/ie', "round((int)\\1/0.621) . ' kph'", $str);

Open in new window