Avatar of hankknight
hankknight
Flag 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
PHP

Avatar of undefined
Last Comment
hernst42

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
hielo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
ifp_support

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

Cem Türk

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

hernst42

Could have been so much easier:

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

Open in new window

Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy