Latitude/Longitude Regular Expression

11,032

Solution 1

You could use something like this:

([0-9.-]+).+?([0-9.-]+)

Since you tagged your question with both PHP and JavaScript, I'll show you how to use it in both.

In PHP:

preg_match('/([0-9.-]+).+?([0-9.-]+)/', $str, $matches);
$lat=(float)$matches[1];
$long=(float)$matches[2];
// coords are in $lat and $long

In JavaScript:

var matches=str.match(/([0-9.-]+).+?([0-9.-]+)/);
var lat=parseFloat(matches[1]);
var long=parseFloat(matches[2]);
// coords are in lat and long

For fun, here's Python too:

import re
match = re.match(r'([0-9.-]+).+?([0-9.-]+)', str)
lat = float(match.group(1))
long = float(match.group(2))
# coords are in lat and long

Solution 2

i Hope this will work

UPDATE

$output= 'ÜT: 51.554644,-0.003976';
function makePerfect($x)
{ 
  return preg_replace('/[^-?0-9\.]/','', $x);
}
$lenLong=explode(',',$output);
$final=array_map('makePerfect',$lenLong);
//debug like this
echo "<pre>";
print_r($final);

display

Array
(
    [0] => 51.554644
    [1] => -0.003976
)

Solution 3

This works for all strings you specified:

$str = "Iphone: 51.554644,-0.003976";

preg_match_all("/(?<lat>[-+]?([0-9]+\.[0-9]+)).*(?<long>[-+]?([0-9]+\.[0-9]+))/", $str, $matches);

$lat = $matches['lat'];
$long = $matches['long'];

var_dump($lat, $long);
Share:
11,032
Pavel
Author by

Pavel

Updated on June 27, 2022

Comments

  • Pavel
    Pavel almost 2 years

    I'm in the middle of developing a Twitter app. While parsing JSON I need to extract latitude and longitude, store them in a database and then later use them in an Android app. Basically, I managed to extract it, but people are sending their tweets from different devices (iPhones, Blackberries, etc.). I'm getting different responses. Here are the examples:

    ÜT: 51.554644,-0.003976
    51.576100, -0.031600
    Iphone: 51.554644,-0.003976
    

    Now my question is: how can I use a regular expression to match latitude and longitude and extract it in a form of array in JavaScript regardless of the word that appears in front of it?