2018年9月26日 星期三

Delphi 執行 Escape編碼及解碼


function Escape(Str: string): string;
var
  I: Integer;
  w: Word ;
begin
  Result := '';
  for I := 1 to Length(Str) do
  begin
    w := Word(Str[I]) ;

    if w in [Ord('0')..Ord('9'),Ord('A')..Ord('Z'),Ord('a')..Ord('z')] then
      Result := Result + Char(w)
    else if w <= 255 then
      Result := Result + '%' + IntToHex(w,2)
    else
      Result := Result + '%u' + IntToHex(w,4);
  end;
end;


function Unescape(const Str:String):String;
  // Sub Function Begin =======================
  function UnescapeUncodeChar(const s:String):WideChar;
  var
    r:Array [0..1] of Byte;
  begin
    HexToBin(
             PChar(LowerCase(s)),
             @r,
             SizeOf(r)
             );
    Result:=WideChar((r[0] shl 8) or r[1]);
  end;
  function UnescapeAnsiChar(const s:String):Char;
  begin
    HexToBin(
             PChar(LowerCase(s)),
             @Result,
             SizeOf(Result)
             );
  end;
  // Sub Functionn End ======================
var
  I:Integer;
  C:Integer;
begin
  C:=1;
  SetLength(Result,Length(Str));

  I:=1;
  while I <= Length(Str) do
  begin
    if Str[I] = '%' then
    begin
      if (I < Length(Str)) and (Str[I+1]='u') then
      begin
        Result[C] := UnescapeUncodeChar(
                                     Copy( Str,I+2,4 )
                                     );//Do with '%uxxxx'
        Inc(i,6);
      end
      else
      begin
        Result[C] := Char(
                           UnescapeAnsiChar( Copy(Str,I+1,2) )
                           );//Do with '%xx'
        Inc(I,3);
      end;
    end
    else
    begin
      Result[C] := WideChar(Str[I]);
      //
      Inc(I);
    end;
    Inc(C);
  end;

  SetLength(Result,C-1);

end;