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 > or & should become & 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
I mean, special character of the text should be converted to correct entities
For example < should become > or & should become & 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
You will most likely have to create the function yourself
function ChangeTextToHTML(S:String) :String;
begin
Result := S;
Result := StringReplace(S,'&','& ',[rfRepla ceAll]);
Result := StringReplace(S,'<','<' ,[rfReplac eAll]);
Result := StringReplace(S,'>','>' ,[rfReplac eAll]);
//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;
function ChangeTextToHTML(S:String)
begin
Result := S;
Result := StringReplace(S,'&','&
Result := StringReplace(S,'<','<'
Result := StringReplace(S,'>','>'
//the rest of the ones you need to convert
end;
You could also encode the whole thing
function ChangeTextToHTML2(S:String
var x:Integer;
begin
Result := '';
for x:=1 to Length(s) do
Result := Result + '&#'+IntToStr(Ord(s[x]))+'
end;
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, '"', '&', '<', '>');
begin
// Allocate memory for the parsing (the largest encoding is 6 bytes from a single byte)
lpszEncode:=AllocMem(Succ(
// Set starting output
lpszPos:=lpszEncode;
// Resource protection
try
// Walk the string
for dwLength:=1 to Length(S) do
begin
lpszEnc:=StrScan(ENCODE_CH
if Assigned(lpszEnc) then
begin
StrCopy(lpszPos, ENCODE_VALS[lpszEnc-ENCODE
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
@rbohac: thanks, just what I was looking for.
procedure TForm1.Button1Click(Sender
begin
Edit1.Text := StringReplace(Edit1.Text, '<', '<', [rfReplaceAll]);
end;