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

折月煮酒 提交于 2019-12-03 16:31:16
^[+-]?\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.

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.

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

The regex approach can't really validate that longitude and latitude are valid, but here's one that would be more precise than the others posted already:

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

This would reject some strings that others' solutions would allow, such as

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

But it would still allow invalid values like this:

361.1234, 123.1234

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!