Page 1 of 1
Forum

Welcome to the Tweaking4All community forums!
When participating, please keep the Forum Rules in mind!

Topics for particular software or systems: Start your topic link with the name of the application or system.
For example “MacOS X – Your question“, or “MS Word – Your Tip or Trick“.

Please note that switching to another language when reading a post will not bring you to the same post, in Dutch, as there is no translation for that post!



Share:
Notifications
Clear all

[Solved] Delphi/Lazarus/FPC - How to Encode and Decode URLs (2 simple functions)

1 Posts
1 Users
0 Reactions
5,439 Views
 Hans
(@hans)
Famed Member Admin
Joined: 12 years ago
Posts: 2859
Topic starter  

While dealing with Encoding and Decoding of URLs (for example space -> %20 and %20 -> space), I used one of my previous functions to encode. But this time I had to write a functions as well to decode, so here ya go:


  URLEncode
  
  Encodes string to be suitable as an URL. (ie. replaces for example a space with %20)
  Example: myencodeURL:=URLEncode(myURL);
}
function URLEncode(s: string): string;
var
  i: integer;
  source: PAnsiChar;
begin
  result := '';
  source := pansichar(s);
  for i := 1 to length(source) do
    if not (source in ['A'..'Z', 'a'..'z', '0'..'9', '-', '_', '~', '.', ':', '/']) then
      result := result + '%' + inttohex(ord(source), 2)
    else
      result := result + source;
end;

{
  URLDecode
  Decodes string to be suitable as an URL.(ie. returns for example a %20 back to space)
  Example: myencodeURL:=URLEncode(myURL);
}
function URLDecode(s: string): string;
var
  i,lengthsource: integer;
  source: PAnsiChar;
begin
  result := '';
  source := pansichar(s);
  lengthsource := length(source);
  i:=1;
  while (i<=lengthsource) do
    begin
      if source[i-1] <> '%' then
        result := result + source[i-1]
      else if (source[i-1] = '%') and (i+1<=lengthsource) then
        try
          begin
            result := result + Chr(Hex2Dec('$'+source+source[i+1]));
            i:=i+2;
          end;
        except
        end
      else
        result := result + source[i-1];
      inc(i);
    end;
end;     

   
ReplyQuote
Share: