hankknight
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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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");
Could have been so much easier:
preg_replace('/(\d+) mph/ie', "round((int)\\1/0.621) . ' kph'", $str);
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.
Open in new window