digout
digout

Reputation: 4252

Get comma-separed latitude and longitude values from a larger body of text

I have a string like the one below:

".......mapsearch"), '52.486683, -4.044363', options......"

I want to retrieve the 2 numbers (long & lat) from the string - I don't mind if I retrieve them together as a single string complete with the comma and space in between.

I know that I want to use an expression to match and ignore anything from the start up to and including the mapsearch"), ' and the same for the end of the string to the ', options pattern.

UPDATE

The string will also contain a range of other characters like { } ( ) = : / and numbers before and after the desired match..

Upvotes: 0

Views: 427

Answers (6)

dvicino
dvicino

Reputation: 1509

$subject = ".....mapsearch\"), '52.486683, -4.044363', options......";
$regex = '/mapsearch\"\), \'(-?[0-9]{1,3}\.[0-9]{6}, -?[0-9]{1,3}\.[0-9]{6})\', options/';
if (preg_match($regex, $subject, $matches)){
    print_r($matches);

This will give you:

Array
(
    [0] => mapsearch"), '52.486683, -4.044363', options
    [1] => 52.486683, -4.044363
)

Upvotes: 0

axiomer
axiomer

Reputation: 2126

In this case, I'd use metalfrog's solution with some changes.

If you're sure that only the string has a comma, nothing else, then explode, and either check if it's an integer/float OR if you know that it's the nth item, just get $array[$n].

Else explode and use this (needs some editing) to determine if it is a coordinate or not.

Upvotes: 0

Stelian Matei
Stelian Matei

Reputation: 11623

You can try this:

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

to extract

52.486683, -4.044363

Upvotes: 0

popthestack
popthestack

Reputation: 506

preg_match("/'([^,]+), ([^']+)'/", $string, $matches);
echo $matches[0]; // 52.486683
echo $matches[1]; // -4.044363

Upvotes: 1

IslandCow
IslandCow

Reputation: 3542

Assuming it's the only numbers in single quotes:

'-?\d+.\d+, -?\d+.\d+'

Upvotes: 0

Dan Breen
Dan Breen

Reputation: 12934

This will work, as ugly as it is:

/mapsearch\"\), '(-?\d+(?:\.\d+)?), (-?\d+(?:\.\d+)?)', options/

The numbers can be negative or positive, and also it will match integers and decimal values. The pattern will return both numbers as a separate group.

Upvotes: 3

Related Questions