Skip to content

Instantly share code, notes, and snippets.

@tranghaviet
Forked from arubacao/latlong.php
Created December 6, 2018 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tranghaviet/8d19eeacda39813e6a6c2884b61ad6b5 to your computer and use it in GitHub Desktop.
Save tranghaviet/8d19eeacda39813e6a6c2884b61ad6b5 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment