Skip to content

Instantly share code, notes, and snippets.

@arubacao
Last active February 10, 2024 00:55
Show Gist options
  • Save arubacao/b5683b1dab4e4a47ee18fd55d9efbdd1 to your computer and use it in GitHub Desktop.
Save arubacao/b5683b1dab4e4a47ee18fd55d9efbdd1 to your computer and use it in GitHub Desktop.
Latitude Longitude Regular Expression Validation PHP
<?php
/**
* Validates a given latitude $lat
*
* @param float|int|string $lat Latitude
* @return bool `true` if $lat is valid, `false` if not
*/
function validateLatitude($lat) {
return preg_match('/^(\+|-)?(?:90(?:(?:\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\.[0-9]{1,6})?))$/', $lat);
}
/**
* Validates a given longitude $long
*
* @param float|int|string $long Longitude
* @return bool `true` if $long is valid, `false` if not
*/
function validateLongitude($long) {
return preg_match('/^(\+|-)?(?:180(?:(?:\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\.[0-9]{1,6})?))$/', $long);
}
/**
* Validates a given coordinate
*
* @param float|int|string $lat Latitude
* @param float|int|string $long Longitude
* @return bool `true` if the coordinate is valid, `false` if not
*/
function validateLatLong($lat, $long) {
return preg_match('/^[-]?(([0-8]?[0-9])\.(\d+))|(90(\.0+)?),[-]?((((1[0-7][0-9])|([0-9]?[0-9]))\.(\d+))|180(\.0+)?)$/', $lat.','.$long);
}
$tests = [
'lat' => [
'0.0','+90.0','-90.0','90.0','+45','-45','45','50','55.55','45,1','A',],
'long' => [
'0.0', '180', '-180', '+180', '179.9', 'A',
],
'lat_long' => [
'90.0,180.0',
'47.1,179.1',
'90.1a,180.1a'
]
];
echo "\033[37;44m:::::::::::: Tests ::::::::::::\033[0m".PHP_EOL;
echo "\033[1mType:\t\tValue:\tResult\033[0m".PHP_EOL;
foreach ($tests['lat'] as $lat) {
echo "Latitude:\t$lat\t\t".((validateLatitude($lat)) ? "\033[32mMATCH\033[0m" : "\033[31mFAIL\033[0m").PHP_EOL;
}
foreach ($tests['long'] as $long) {
echo "Longitude:\t$long\t\t".((validateLongitude($long)) ? "\033[32mMATCH\033[0m" : "\033[31mFAIL\033[0m").PHP_EOL;
}
foreach ($tests['lat_long'] as $lat_long) {
$geo = explode(",", $lat_long);
echo "Lat,Long:\t$lat_long\t".((validateLatLong($geo[0],$geo[1])) ? "\033[32mMATCH\033[0m" : "\033[31mFAIL\033[0m").PHP_EOL;
}
@arubacao
Copy link
Author

arubacao commented Jun 6, 2016

screenshot

@serialc
Copy link

serialc commented Jan 12, 2018

Hi,

Nice piece of code. The test case for Lat,Long value of '49,123' fails. Why not make integer Lat,Long pair values valid as well as you do for the individual regex?

Cheers,
C-

@serialc
Copy link

serialc commented Jan 12, 2018

I updated the LatLong regex so it works when integers are provided:
return preg_match('/^[-]?((([0-8]?[0-9])(\.(\d+))?)|(90(\.0+)?)),[-]?((((1[0-7][0-9])|([0-9]?[0-9]))(\.(\d+))?)|180(\.0+)?)$/', $lat.','.$long);

Cheers,
C-

Copy link

ghost commented May 8, 2018

Thank you @serialc for correcting the code, I noticed the issue as well.

@alexc-hollywood
Copy link

Suggest changing float length from {1,6} to {1,20} - ran into this problem recently while working with GPS receivers, who go into ridiculous accuracy.

@pmochine
Copy link

pmochine commented Oct 1, 2018

Because google is giving me much more decimals I needed to update the regex

For example:
'latLng' => [
'lat' => 52.52000659999999,
'lng' => 13.404953999999975
],

would not work. So I changed it like:

^(+|-)?(?:90(?:(?:.0{1,14})?)|(?:[0-9]|[1-8][0-9])(?:(?:.[0-9]{1,14})?))$

@IRGeekSauce
Copy link

I'm searching for google formatted locations as well. Thanks for mentioning that @pmochine.

@phroggyy
Copy link

phroggyy commented Nov 20, 2019

here's a smaller implementation:

function validateLatitude(float $latitude): bool
{
    return $latitude <= 90 && $latitude >= -90;
}

function validateLongitude(float $longitude): bool
{
    return $longitude <= 180 && $longitude > -180;
}

@kuz1toro
Copy link

kuz1toro commented Jan 6, 2020

heres very shorted version :)
function validateCoordinate($latitude, $longitude) { return is_numeric($latitude) && is_numeric($longitude); }

@phroggyy
Copy link

phroggyy commented Jan 6, 2020

@kuz1toro that allows invalid coordinates such as 104,207

Copy link

ghost commented Mar 9, 2020

  /**
 * Validates a given coordinate
 *
 * @param float|int|string $lat Latitude
 * @param float|int|string $long Longitude
 * @return bool `true` if the coordinate is valid, `false` if not
 */
function is_coordinate($lat, $long) {

    $lat_pattern  = '/\A[+-]?(?:90(?:\.0{1,18})?|\d(?(?<=9)|\d?)\.\d{1,18})\z/x';
    $long_pattern = '/\A[+-]?(?:180(?:\.0{1,18})?|(?:1[0-7]\d|\d{1,2})\.\d{1,18})\z/x';

    if (preg_match($lat_pattern, $lat) && preg_match($long_pattern, $long)) {
        return true;
    } else {
        return false;
    }
}


/* These are two points in Turkey */
$point1 = array('lat' => 41.008610, 'long' => 28.971111); // Istanbul
$point2 = array('lat' => 39.925018, 'long' => 32.836956); // Anitkabir

echo '<br>';

if(!is_coordinate($point1['lat'], $point1['long'])){
    echo 'Invalid coordinate.';
} else {
    echo 'The current coordinate.';
}

echo '<br>';

if(!is_coordinate($point2['lat'], $point2['long'])){
    echo 'Invalid coordinate.';
} else {
    echo 'The current coordinate.';
}

  1. https://github.com/aliyilmaz/Mind/blob/master/src/Mind.php#L1449
  2. https://github.com/aliyilmaz/Mind/blob/master/tests/is_coordinate.php
  3. https://github.com/aliyilmaz/Mind/blob/master/tests/validate.php

@Bazzly
Copy link

Bazzly commented Nov 4, 2020

I don't think this we work for wgs84 projection? like 384943.343,344343.004 if yes please suggest anyone perfect. thanks

@hamog
Copy link

hamog commented Apr 24, 2021

I use this regex and it works correct:

latitude:

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

longitude:

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

@Bazzly
Copy link

Bazzly commented Apr 28, 2021

Northings and eastings from Nigeria can use this 'regex:/^\d{1,6}(.\d{1,3})?$/'

@Bazzly
Copy link

Bazzly commented Apr 28, 2021

I use this regex and it works correct:

latitude:

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

longitude:

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

i will try this on lat an long thanks

@paulvancity
Copy link

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

I removed the comma and it still returns 1, is there a way to have it so it fails if no comma?

@Bazzly
Copy link

Bazzly commented Mar 10, 2022

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

I removed the comma and it still returns 1, is there a way to have it so it fails if no comma?

Maybe you should try and elaborate on what the problem is .

@mancy-gif
Copy link

but it is not valid in the case of "--",
I used this regex but it accepted"--78798989898" case which is wrong, Can anyone suggest me something?

@Bazzly
Copy link

Bazzly commented May 2, 2022

but it is not valid in the case of "--", I used this regex but it accepted"--78798989898" case which is wrong, Can anyone suggest me something?

can you tell me the format of the result you want to obtain?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment