Get parameters from URL, get substrings in a query

2019-07-19 18:57发布

I want to get the values of some parameters in a URL, I know the idea but I don't know how to do get them.

I have an string that is an URL:

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

I want to detect the sub-strings "to[" and get the numbers 293321147507203,293321147507202 and store them in a table.

I know the process is detect the sub-string to[ and then get the sub-string that is 3 character (or 6 not sure if it counts from the beginning of "to[" and then get the number, always is a 15 digit number.

2条回答
闹够了就滚
2楼-- · 2019-07-19 19:06

Here you go, a slightly more general solution for parsing query string, supporting string and integer keys, as well as 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

For URL fbconnect://success?to[0]=213322147507203&to[1]=223321147507202&request=524210977333164&complex+name=hello%20cruel+world&to[string+key]=123 it returns:

{
  ["complex name"]="hello cruel world",
  request="524210977333164",
  to={ [0]="213322147507203", [1]="223321147507202", ["string key"]="123" } 
}
查看更多
一纸荒年 Trace。
3楼-- · 2019-07-19 19:20
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
查看更多
登录 后发表回答