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

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


 Hans
(@hans)
Noble Member Admin
Joined: 8 years ago
Posts: 2018
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

Like what you see and you'd like to help out? 

The best way to help is of course by assisting others with their questions here in the forum, but you can also help us out in other ways:

- Do your shopping at Amazon, it will not cost you anything extra but may generate a small commission for us,
- send a cup of coffee through PayPal ($5, $10, $20, or custom amount),
- become a Patreon,
- donate BitCoin (BTC), or BitCoinCash (BCH).

Share: