如何确定 PHP 字符串是否仅包含纬度和经度
我必须使用可能包含纬度/经度数据的字符串,如下所示:
$query = "-33.805789,151.002060";
$query = "-33.805789, 151.002060";
$query = "OVER HERE: -33.805789,151.002060";
就我的目的而言,前两个字符串是正确的,但最后一个字符串不正确。我正在尝试找出一种匹配模式,该模式将匹配以逗号分隔的纬度和经度,或者逗号和空格。但是,如果字符串中包含除数字、空格、点、减号和逗号之外的任何内容,则匹配失败。
希望这是有道理的,TIA!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
开头的
^
和结尾的$
确保它匹配完整的字符串,而不仅仅是其中的一部分。The
^
at the start and$
at the end make sure that it matches the complete string, and not just a part of it.按照其他答案中的建议,使用正则表达式解决是最简单的。这是一个也可行的分步方法:
此解决方案将接受逗号后的任意数据:
将正常通过。
正如 Frank Farmer 正确指出的那样,
is_numeric
还将识别科学记数法。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:
This solution will accept arbitrary data after a comma:
will pass as ok.
As Frank Farmer correctly notes,
is_numeric
will also recognize scientific notation.正则表达式方法无法真正验证经度和纬度是否有效,但这里的方法比已经发布的其他方法更精确:
这将拒绝其他解决方案允许的某些字符串,例如
但它仍然允许无效值像这样:
如果您需要认真的验证,您最好的选择是创建一个类来存储和验证这些坐标。
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:
This would reject some strings that others' solutions would allow, such as
But it would still allow invalid values like this:
Your best bet -- if you need serious validation -- is to create a class to store and validate these coordinates.