Title: Search and Replace in a string
Question: How can I search for a substring and replace all by another one?
Answer:
{ The function searches for a substring 'SearchFor' in a string
'Str' and replaces all found substrings by 'ReplaceStr' }
function ReplaceIn(SearchFor, ReplaceStr, Str : String): String;
var
Dummy, st : String;
i : integer;
begin
{ make a temp. copy of the Str }
st := Str;
{ first position of the substring }
i := Pos(SearchFor, St);
Dummy := '';
{ search lasts while the specified substring is found }
while i 0 do
begin
Dummy := Dummy + Copy(St, 0, i - 1) + ReplaceStr;
st := copy(st, i + length(SearchFor), length(st)+1);
i := Pos(SearchFor, St);
end;
{ result: the substrings replaced by 'ReplaceStr' }
result := Dummy + st;
end;