【问题标题】:What regex expression will check GPS values?什么正则表达式将检查 GPS 值?
【发布时间】:2011-08-18 20:30:12
【问题描述】:

我让用户通过表格输入 GPS 值,他们都有相同的表格,一些例子:

49.082243,19.302628  

48.234142,19.200423  

49.002524,19.312578

我想使用 PHP 检查输入的值(我猜是使用 preg_match()),但由于我不擅长正则表达式(哦,我笨,我终于应该学会了,我知道),我不知道不知道怎么写。

显然应该是:
2x(数字)、1x(点)、6x(数字)、1x(逗号)、2x(数字)、1x(点)、6x(数字)

有什么建议可以用正则表达式写吗?

【问题讨论】:

    标签: php regex preg-match


    【解决方案1】:

    我看到的其他答案没有考虑到经度从-180到180,纬度从-90到90。

    正确的正则表达式是(假设顺序是“纬度,经度”):

    /^(-?[1-8]?\d(?:\.\d{1,6})?|90(?:\.0{1,6})?),(-?(?:1[0-7]|[1-9])?\d(?:\.\d{1,6})?|180(?:\.0{1,6})?)$/
    

    此正则表达式涵盖纬度不小于 -90 且不大于 90 以及经度不小于 -180 且不大于 180,同时允许它们输入整数和任意小数位从 1 到 6,如果您想获得更高的精度,只需将 {1,6} 更改为 {1,x} 其中 x 是小数位数

    此外,如果您在第 1 组捕获,您将获得纬度,在第 2 组捕获将获得经度。

    【讨论】:

      【解决方案2】:

      类似:

      /^(-?\d{1,2}\.\d{6}),(-?\d{1,2}\.\d{6})$/
      
      • ^ 输入开始处的锚点
      • -? 允许但不需要负号
      • \d{1,2} 需要 1 或 2 个十进制数字
      • \. 需要小数点
      • \d{6} 需要 6 个十进制数字
      • , 匹配单个逗号
      • (重复前 5 个项目符号)
      • $ 锚点在输入的末尾

      我已包含捕获括号以允许您提取各个坐标。如果您不需要,请随意省略它们。

      全方位有用的正则表达式参考:http://www.regular-expressions.info/reference.html

      【讨论】:

      • 请注意,一个 GPS 值是由逗号分隔的两个值。
      • 谢谢,这非常有帮助!在 6 分钟内接受你的答案,当冷却时间允许我 :)
      • 只是一个快速修复,^ 是输入的开始,$ 是结束输入
      • @Michael d'ahhh 一个草率的错误。接得好!谢谢,已修复。
      • 另一个小问题,这不会让您输入大于 100 度的坐标。经度和纬度都是180到-180,OP的规格是错误的。
      【解决方案3】:
      /$-?\d{2}\.\d{6},-?\d{2}\.\d{6}^/
      

      【讨论】:

        【解决方案4】:

        扩展另一个答案:

        /^-?\d\d?\.\d+,-?\d\d?\.\d+$/
        

        【讨论】:

          【解决方案5】:

          根据您的示例,可以这样做:

          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
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-10-16
            • 1970-01-01
            • 1970-01-01
            • 2015-03-12
            • 2011-12-19
            • 1970-01-01
            • 2022-06-16
            相关资源
            最近更新 更多