Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a PHP string ONLY contains latitude and longitude

I have to work with strings which may contain Lat/Long data, like this:

$query = "-33.805789,151.002060";
$query = "-33.805789, 151.002060";
$query = "OVER HERE: -33.805789,151.002060";

For my purposes, the first 2 strings are correct, but the last one isn't. I am trying to figure out a match pattern which would match a lat and long separated by a comma, or a comma and a space. But if it has anything in the string other than numbers, spaces, dots, minus signs and commas, then it should fail the match.

Hope this makes sense, and TIA!

like image 812
Alexia Avatar asked Feb 27 '10 18:02

Alexia


2 Answers

^[+-]?\d+\.\d+, ?[+-]?\d+\.\d+$

The ^ at the start and $ at the end make sure that it matches the complete string, and not just a part of it.

like image 83
Wim Avatar answered Sep 20 '22 12:09

Wim


It's simplest to solve with a regex as suggested in the other answers. Here is a step-by-step approach that would work too:

$result = explode(",", $query);  // Split the string by commas
$lat = trim($result[0]);         // Clean whitespace
$lon = trim($result[1]);         // Clean whitespace

if ((is_numeric($lat)) and (is_numeric($lon))) echo "Valid coordinates!";

This solution will accept arbitrary data after a comma:

 "-33.805789,151.002060,ABNSBOFVJDPENVÜE";

will pass as ok.

As Frank Farmer correctly notes, is_numeric will also recognize scientific notation.

like image 23
Pekka Avatar answered Sep 21 '22 12:09

Pekka