1

I am trying to replace some wildcards in a html code to send it via mailing. Problem is when I try to replace the string with wildcard 'España$country$' with the string 'España', the result would be 'EspañaEspa?a'. I had the same problem before in Delphi 7 and I solved it by using the function 'UTF8Encode('España')' but it does not work on Delphi 10.

I have tried with 'España', 'UTF8Encode('España')' and 'AnsiToUTF8('España')'. I also tried to change the function StringReplace with ReplaceStr and ReplaceText, with same result.

...... var htmlText : TStringList; ...... htmlText := TStringList.Create; htmlText.LoadFromFile('path.html'); htmlText.StringReplace(htmlText.Text, '$country$', UTF8Encode('España'), [rfReplaceAll]); htmlText.SaveToFile('anotherpath.html'); ...... 

This "stringreplace" along with "utf8encode" works well in Delphi7, showing 'España', but not in delphi 10, where you can read 'Espa?a' in the anotherpath.html.

1 Answer 1

2

The Delphi 7 string type, and consequently TStrings, did not support Unicode. Which is why you needed to use UTF8Encode.

Since Delphi 2009, Unicode is supported, and string maps to UnicodeString, and TStrings is a collection of such strings. Note that UnicodeString is internall encoded as UTF-16 although that's not a detail that you need to be concerned with here.

Since you are now using a Delphi that supports Unicode, your code can be much simpler. You can now write it like this:

htmlText.Text := StringReplace(htmlText.Text, '$country$', 'España', [rfReplaceAll]); 

Note that if you wish the file to be encoded as UTF-8 when you save it you need to specify that when you save it. Like this:

htmlText.SaveToFile('anotherpath.html', TEncoding.UTF8); 

And you may also need to specify the encoding when loading the file in case it does not include a UTF-8 BOM:

htmlText.LoadFromFile('path.html', TEncoding.UTF8); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.