Announcement

Collapse
No announcement yet.

URL Encode / Decode

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • URL Encode / Decode

    Been doing some work on URLs lately. Have found the following functions for URL Encoding / Decoding quite useful. These functions will:
    • Convert un-encoded URL string to its encoded representation. http://lua docs/ to http%3A%2F%2Flua%20docs%2F
    • Revert URL-encoded string, back to its original unencoded form. http%3A%2F%2Flua%20docs%2F to http://lua docs/

    Code:
    [B]-[I]- URL Encode:[/I][/B]
    function encodeChar(chr)
        return string.format("%%%X",string.byte(chr))
    end
     
    function encodeString(str)
        local output, sURL = string.gsub(str,"[^%w]",encodeChar)
        return output
    end
     
    -- Example Usage:
    Debug.Clear();
    Debug.ShowWindow(true);
    Debug.Print(encodeString("http://lua docs/"));
    Code:
    [B][I]-- URL Decode:[/I][/B]
    function decodeChar(hex)
        return string.char(tonumber(hex,16))
    end
     
    function decodeString(str)
        local output, sURL = string.gsub(str,"%%(%x%x)",decodeChar)
        return output
    end
    
    -- Example Usage:
    Debug.Clear();
    Debug.ShowWindow(true);
    Debug.Print(decodeString("http%3A%2F%2Flua%20docs%2F"));
    After searching forum to check if something like this has already been done, did find apparently that Riz had actually done a DLL for it at some stage. Mentioned here But the link to it seems to be long gone. So, fortuitously then, you won't have to mess around with String.Replace - you can just use this baby, instead. Cool bananas.
    Attached Files

  • #2
    interesting example, you gave me an idea about a favorite folder link websites and this example could help me thanks!
    Last edited by naxo; 06-17-2018, 02:35 AM.

    Comment


    • #3
      Alternate version wrapped up as a single function:
      Source: http://lua-users.org
      Code:
      [I][B]-- URL Encode:[/B][/I]
      function url_encode(str)
          if (str) then
              str = string.gsub (str, "\n", "\r\n")
              str = string.gsub (str, "([^%w %-%_%.%~])",
                  function (c) return string.format ("%%%02X", string.byte(c)) end)
              str = string.gsub (str, " ", "+")
          end
          return str    
      end
      Code:
      [I][B]-- URL Decode:[/B][/I]
      function url_decode(str)
          str = string.gsub (str, "+", " ")
          str = string.gsub (str, "%%(%x%x)",
              function(h) return string.char(tonumber(h,16)) end)
          str = string.gsub (str, "\r\n", "\n")
          return str
      end
      Example usage attached.
      Attached Files

      Comment

      Working...
      X