从URL中获取参数,在查询字符串中获取子字符串并将它们存储在一个表中。

我想要获取 URL 中某些参数的值,我知道这个想法,但不知道如何去实现。

我有一个字符串是一个 URL:

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

我想要检测子字符串"to["并获取数字293321147507203、293321147507202,然后将它们存储在一个表格中。

我知道这个过程是检测子字符串"to[",然后获取长度为3个字符(或6个,不确定是从"to["的开头计数还是从整个 URL 的开头计数),接着获取该数字,它总是一个15位数字。

点赞
用户1847592
用户1847592
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  -- 将值存储为字符串
end
print(some_table[0], some_table[1]) --> 213322147507203 223321147507202
2014-07-22 11:54:12
用户521032
用户521032

下面是一个稍微通用一些的查询字符串解析函数,支持字符串和整数键名,以及 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"
  }
}
2014-07-22 12:32:55