2

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 Answers 2

3
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
Sign up to request clarification or add additional context in comments.

Comments

2

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" } 
}

2 Comments

What about automatic converting of + into space character and %xx into corresponding symbols?
@EgorSkriptunoff, fixed it, by adding URL decoding inspired by this SO answer. Thanks for pointing that out :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.