Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php Validate latitude/longitude strings in decimal format

Tags:

regex

php

Alright I have what I would call a massive list of longitude and latitude coordinates. That said I also have a handful of sources I pull these coordinates in from. Some of them come from get/post methods which can cause potential security holes in my site/service. So I am trying to figure out how to validate longitude and latitude via PHP. I was thinking something regex via preg_match. But I could be wrong, maybe there's an easier way someone would like to suggest. I've tried my own concepts, and I have tried various internet brew concepts of trying to find a regex pattern that will validate these for me via preg_match (or similar again if you got a better suggestion I am all ears).

My Last failed attempt prior to finally caving in and coming here was..

preg_match('^(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)$', $geoResults['latitude'])) 

which yields " preg_match() [function.preg-match]: No ending delimiter '^' found " as my error. Last couple attempts I have tried yielded that error so I have no idea what it is or means.

like image 774
chris Avatar asked Sep 26 '11 00:09

chris


2 Answers

It's a bit old question, but anyway I post my solution here:

preg_match('/^[-]?(([0-8]?[0-9])\.(\d+))|(90(\.0+)?);[-]?((((1[0-7][0-9])|([0-9]?[0-9]))\.(\d+))|180(\.0+)?)$/', $geoResults['latlng']); 

I assumed here that u split lat. from lng. by semicolon. If u want to check only lat. or only lng. here are regexp's;

Rgx for lat.:

/^[-]?(([0-8]?[0-9])\.(\d+))|(90(\.0+)?)$/ 

Rgx for lng.:

/^[-]?((((1[0-7][0-9])|([0-9]?[0-9]))\.(\d+))|180(\.0+)?)$/ 

Here is an improved online demo: https://regex101.com/r/bV5fA1/1

like image 154
Doro Avatar answered Oct 06 '22 00:10

Doro


Add forward slashes to the beginning and end of the match sequence to make it valid regex syntax:

preg_match('/^(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)$/', $geoResults['latitude']); 

For your question on whether to use regular expressions (regex) or not, in this case using regex (PCRE preg_match()) is the best way to secure your site. When matching variable complex string arrangements, regex is the way to go. It's common for developers to turn to regex for matching a static string such as 'abc'. This is when strpos() or str_replace() are better choices.

like image 41
Chris Bornhoft Avatar answered Oct 06 '22 02:10

Chris Bornhoft