I would like to convert a lat/lng string to decimals in php. An example:
N47° 30.5951' = 47+(30.59517/60) = 47.509918333
Is there any easy way to do that, regular expression?
Thanks
You can't do arithmetic in a normal regex replace, but you could write a callback function and use preg_replace_callback.
function matches_to_decimal($matches) {
return $matches[2] + ($matches[3]/60);
}
$inputString = "N47° 30.5951'";
$resultDecimal = preg_replace_callback('/(N|S)(\d+)° (\d+\.?\d*)\'/',
"matches_to_decimal",
$inputString);
By the way, latitude and longitude are usually written 47°30'35"N, 123°56'12"W, so you could adjust the regex and callback function accordingly.
preg_match('/^N(\d+)\° (\d+(?:\.\d+)?)\'$/i', "N47° 30.5951'", $bits);
$coord = floatval($bits[1]) + (floatval($bits[2])/60);
Forgive my ignorance of lat long, if i'm off the mark.
not sure if E and W belong here, but except that:
$regex = "/[EWNS](\d{1,3})°\ (\d{1,3}\.\d{0,10})'/";
if (preg_match($regex, "N47° 30.5951'", $matches))
{
$result = $matches[1] + ((float) $matches[2] / 60);
}