Question

On search, I want to check if query is latitude and longitude or just text search with PHP.

$query = '-122.0307642, 37.3316930';

latitude and longitude can have '-' in them also.

What preg_match pattern it will be for this?

Was it helpful?

Solution

The following regex will match two numbers (with or without a negative sign, separated by a comma) of the format a.b where a and b are digit-sequences of minimum length one.

(-?\d+\.\d+)\s*,\s*(-?\d+\.\d+)

OTHER TIPS

Something like this:

(-?\d+(?:\.\d+)?)(?:,\s*|\s+)(-?\d+(?:\.\d+)?)

This will net you two matches, which you can then cast to floats and check against lat/lng bounds.

This will also allow the two numbers to be separated by space. If you want to only allow a comma, use:

(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top