Php 什么正则表达式将检查GPS值?
我让用户通过表单输入GPS值,他们都有相同的表单,例如:Php 什么正则表达式将检查GPS值?,php,regex,preg-match,Php,Regex,Preg Match,我让用户通过表单输入GPS值,他们都有相同的表单,例如: 49.082243,19.302628 48.234142,19.200423 49.002524,19.312578 我想使用PHP检查输入的值(我想是使用preg_match()),但由于我不擅长正则表达式(哦,我真傻,我终于应该学会了,我知道),我不知道如何编写表达式 显然应该是: 2x(数字)、1x(点)、6x(数字)、1x(逗号)、2x(数字)、1x(点)、6x(数字) 有没有关于如何在正则表达式中编写的建议?类似
49.082243,19.302628
48.234142,19.200423
49.002524,19.312578
我想使用PHP检查输入的值(我想是使用preg_match()
),但由于我不擅长正则表达式(哦,我真傻,我终于应该学会了,我知道),我不知道如何编写表达式
显然应该是:2x(数字)、1x(点)、6x(数字)、1x(逗号)、2x(数字)、1x(点)、6x(数字) 有没有关于如何在正则表达式中编写的建议?类似于:
/^(-?\d{1,2}\.\d{6}),(-?\d{1,2}\.\d{6})$/
将锚定在输入的开始处^
允许但不要求负号-?
需要1或2位十进制数字\d{1,2}
需要小数点\。
需要正好6位十进制数字\d{6}
匹配一个逗号,
- (重复前5个项目)
将锚定在输入的末尾$
全面有用的正则表达式参考:在另一个答案上展开:
/^-?\d\d?\.\d+,-?\d\d?\.\d+$/
我看到的其他答案没有考虑经度从-180到180,纬度从-90到90 适用于此的正则表达式为(假设顺序为“纬度,经度”): 这个正则表达式包括纬度不小于-90且不大于90,经度不小于-180且不大于180,同时允许它们输入整数以及从1到6的任何小数位数,如果您想允许更高的精度,只需将{1,6}更改为{1,x},其中x是小数位数
此外,如果在组1上进行捕获,则获得纬度,在组2上进行捕获,则获得经度。根据您的示例,这将完成以下操作:
if (preg_match('/(-?[\d]{2}\.[\d]{6},?){2}/', $coords)) {
# Successful match
} else {
# Match attempt failed
}
说明:
( # Match the regular expression below and capture its match into backreference number 1
- # Match the character “-” literally
? # Between zero and one times, as many times as possible, giving back as needed (greedy)
[\d] # Match a single digit 0..9
{2} # Exactly 2 times
\. # Match the character “.” literally
[\d] # Match a single digit 0..9
{6} # Exactly 6 times
, # Match the character “,” literally
? # Between zero and one times, as many times as possible, giving back as needed (greedy)
){2} # Exactly 2 times
请注意,一个GPS值是用逗号分隔的两个值。谢谢,这非常有用!6分钟后接受你的答案,当冷却时间允许我:)只是一个快速修复,^是输入的开始,$是结束input@Michael这是个草率的错误。抢手货谢谢,修正了。另一个小问题,这将不允许你输入大于100度的坐标。经度和纬度都是180到-180,OP的规格是错误的。
if (preg_match('/(-?[\d]{2}\.[\d]{6},?){2}/', $coords)) {
# Successful match
} else {
# Match attempt failed
}
( # Match the regular expression below and capture its match into backreference number 1
- # Match the character “-” literally
? # Between zero and one times, as many times as possible, giving back as needed (greedy)
[\d] # Match a single digit 0..9
{2} # Exactly 2 times
\. # Match the character “.” literally
[\d] # Match a single digit 0..9
{6} # Exactly 6 times
, # Match the character “,” literally
? # Between zero and one times, as many times as possible, giving back as needed (greedy)
){2} # Exactly 2 times