Link to home
Start Free TrialLog in
Avatar of LeTay
LeTay

asked on

Encode simple text string to html format

Just need a sample of Delphi 7 code to convert a text (I read it from a DB) in html code.
I mean, special character of the text should be converted to correct entities
For example < should become &gt;  or & should become &amp; etc....
In fact the equivalent of the ASP server.htmlencode method

var
 S:string;
begin
 .../... read here from some source to S
 S := ????(S)
end
Avatar of Ivanov_G
Ivanov_G
Flag of Bulgaria image


procedure TForm1.Button1Click(Sender: TObject);
begin
  Edit1.Text := StringReplace(Edit1.Text, '<', '&lt', [rfReplaceAll]);
end;
Avatar of rbohac
rbohac

You will most likely have to create the function yourself

function ChangeTextToHTML(S:String):String;
begin
  Result := S;
  Result := StringReplace(S,'&','&amp;',[rfReplaceAll]);
  Result := StringReplace(S,'<','&lt;',[rfReplaceAll]);
  Result := StringReplace(S,'>','&gt;',[rfReplaceAll]);
  //the rest of the ones you need to convert
end;

You could also encode the whole thing

function ChangeTextToHTML2(S:String):String;
var x:Integer;
begin
  Result := '';
  for x:=1 to Length(s) do
    Result := Result + '&#'+IntToStr(Ord(s[x]))+';';
end;
Avatar of Russell Libby

Just another example....

function HTMLEncode(S: String): String;
var  dwLength:      Integer;
     lpszEnc:       PChar;
     lpszEncode:    PChar;
     lpszPos:       PChar;
const
  ENCODE_CHARS:     PChar =  #10#13#34#38#60#62#0;
  ENCODE_VALS:      Array [0..5] of PChar = ('<br>', #0, '&quot;', '&amp;', '&lt;', '&gt');
begin

  // Allocate memory for the parsing (the largest encoding is 6 bytes from a single byte)
  lpszEncode:=AllocMem(Succ(6 * Length(S)));

  // Set starting output
  lpszPos:=lpszEncode;

  // Resource protection
  try
     // Walk the string
     for dwLength:=1 to Length(S) do
     begin
        lpszEnc:=StrScan(ENCODE_CHARS, S[dwLength]);
        if Assigned(lpszEnc) then
        begin
           StrCopy(lpszPos, ENCODE_VALS[lpszEnc-ENCODE_CHARS]);
           lpszPos:=StrEnd(lpszPos);
        end
        else
        begin
           lpszPos^:=S[dwLength];
           Inc(lpszPos);
        end;
     end;
  finally
     // Set result
     result:=lpszEncode;
     // Free memory
     FreeMem(lpszEncode);
  end;

end;

-------------

Russell
ASKER CERTIFIED SOLUTION
Avatar of Deti
Deti
Flag of Poland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@rbohac: thanks, just what I was looking for.