【问题标题】:Get parameters from URL, get substrings in a query string and store them in a table从 URL 获取参数,获取查询字符串中的子字符串并将它们存储在表中
【发布时间】:2014-09-13 04:14:57
【问题描述】:

我想获取 URL 中某些参数的值,我知道这个想法,但我不知道如何获取它们。

我有一个 URL 字符串:

local url="fbconnect://success?to[0]=213322147507203&to[1]=223321147507202&request=524210977333164"

我想检测子字符串“to[”并获取数字 293321147507203,293321147507202 并将它们存储在表格中。

我知道这个过程是检测子字符串to[然后获取3个字符的子字符串(或者6不确定它是否从“to [”的开头开始计数然后获取数字,总是一个 15 位数字。

【问题讨论】:

    标签: string parsing url lua substring


    【解决方案1】:
    local url="fbconnect://success?to[0]=213322147507203&to[1]=223321147507202&request=524210977333164"
    local some_table = {}
    for i, v in url:gmatch'to%[(%d+)]=(%d+)' do
       some_table[tonumber(i)] = v  -- store value as string
    end
    print(some_table[0], some_table[1]) --> 213322147507203 223321147507202
    

    【讨论】:

      【解决方案2】:

      给你一个更通用的解析查询字符串的解决方案,支持字符串和整数键,以及implicit_integer_keys[]

      function url_decode (s)
          return s:gsub ('+', ' '):gsub ('%%(%x%x)', function (hex) return string.char (tonumber (hex, 16)) end)
      end 
      
      function query_string (url)
          local res = {}
          url = url:match '?(.*)$'
          for name, value in url:gmatch '([^&=]+)=([^&=]+)' do
              value = url_decode (value)
              local key = name:match '%[([^&=]*)%]$'
              if key then
                  name, key = url_decode (name:match '^[^[]+'), url_decode (key)
                  if type (res [name]) ~= 'table' then
                      res [name] = {}
                  end
                  if key == '' then
                      key = #res [name] + 1
                  else
                      key = tonumber (key) or key
                  end
                  res [name] [key] = value
              else
                  name = url_decode (name)
                  res [name] = value
              end
          end
          return res
      end
      

      对于 URL fbconnect://success?to[0]=213322147507203&to[1]=223321147507202&request=524210977333164&complex+name=hello%20cruel+world&to[string+key]=123 它返回:

      {
        ["complex name"]="hello cruel world",
        request="524210977333164",
        to={ [0]="213322147507203", [1]="223321147507202", ["string key"]="123" } 
      }
      

      【讨论】:

      • + 自动转换为空格字符,%xx 自动转换为对应的符号呢?
      • @EgorSkriptunoff,通过添加受this SO answer 启发的 URL 解码来修复它。感谢您指出这一点:)
      猜你喜欢
      • 2017-07-20
      • 1970-01-01
      • 2013-03-01
      • 2017-12-09
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多