3

I have a URL and would like to parse its Parameter out of it, like:

function unescape (s)
  s = string.gsub(s, "+", " ")
  s = string.gsub(s, "%%(%x%x)", function (h)
        return string.char(tonumber(h, 16))
      end)
  return s
end

function parseurl (s,param)
for k, v in string.gmatch( s, "([^&=?]+)=([^&=?]+)" ) do
    --t[k] = v
    if k == param then
        --print (k.." "..v)
        return unescape(v)
    end
end

s = "http://www.page.com/link.php uname=Hans+Testmann&uemail=myemail%40gmail.com&utext=Now+this+is+working+great.%0D%0A++&mdt=1#&mydays:themeupload"s

Than I would call it and get Results like after -->

parseurl (s, "uname")      --> "Hans Testmann"
parseurl (s, "uemail")     --> "[email protected]"
parseurl (s, "utext")      --> "Now this is working great"

I already fixed a lot and seems to work, but could you look how its possible to improve?

2
  • 1
    Perhaps codereview.stackexchange.com. Commented Mar 7, 2015 at 15:20
  • The first case 'uname' does not work. You need to remove the URL for the gmatch to work. Add this line in parseurl() before the for loop: s = s:match('%s+(.+)') Commented Mar 7, 2015 at 23:15

1 Answer 1

6

I would return all parameters in a table and use like so:

function urldecode(s)
  s = s:gsub('+', ' ')
       :gsub('%%(%x%x)', function(h)
                           return string.char(tonumber(h, 16))
                         end)
  return s
end

function parseurl(s)
  s = s:match('%s+(.+)')
  local ans = {}
  for k,v in s:gmatch('([^&=?]-)=([^&=?]+)' ) do
    ans[ k ] = urldecode(v)
  end
  return ans
end

t = parseurl(s)
print(t.uname ) --> 'Hans Testmann'
print(t.uemail) --> '[email protected]'
print(t.utext ) --> 'Now this is working great'
Sign up to request clarification or add additional context in comments.

Comments

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.