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

I need to work with strings that may contain Lat / Long data, for example:

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

For my purposes, the first 2 lines are correct, but the last is not. I am trying to figure out a matching pattern that will match the lat length and the length separated by comma or comma and space. But if there is something else in the line, except for numbers, spaces, periods, minus signs and commas, then this should not coincide.

Hope this makes sense, and TIA!

+4
source share
4 answers
 ^[+-]?\d+\.\d+, ?[+-]?\d+\.\d+$ 

^ at the beginning and $ at the end, make sure that it matches the full line, and not just its parts.

+10
source

The easiest way to solve this is with regex as suggested in other answers. Here is a step-by-step approach that will 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 decision will accept arbitrary decimal data:

  "-33.805789,151.002060,ABNSBOFVJDPENVÜE"; 

will pass as ok.

As Frank Farmer correctly points out, is_numeric also recognizes scientific notation.

+1
source
 /^-*\d*\.\d+,[\b]*-*\d*\.\d+$/ 
0
source

The regex approach cannot really confirm that longitude and latitude are valid, but here is one that would be more accurate than others already published:

 /^\s*-?\d{1,3}\.\d+,\s*\d{1,3}\.\d+\s*$/ 

This will reject some lines that other solutions will allow, for example

 -1-23-1-,210- --123.1234,123.1234 

But he would still have invalid values:

 361.1234, 123.1234 

Your best bet - if you need a serious check - is to create a class to store and check these coordinates.

0
source

Source: https://habr.com/ru/post/1302609/


All Articles