php Validate latitude/longitude strings in decimal format
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
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.