We help IT Professionals succeed at work.

Convert phrase to kph from mph

hankknight
hankknight asked
on
1,979 Views
Last Modified: 2010-05-18
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
Comment
Watch Question

CERTIFIED EXPERT
Expert of the Year 2008
Top Expert 2008
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
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ürkSenior Software Engineer

Commented:
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

Top Expert 2007

Commented:
Could have been so much easier:

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

Open in new window

Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.