Expand/Shrink

substitute

Definition: sequence text = substitute(sequence text, object s, r, integer limit=-1)
Description: Replace at most limit instances, or all if limit is -1, of s in text with r.
s and r can be strings or individual characters (or one of each).
pwa/p2js: Supported.
Comments: Ideal for extensive text manipulation, eg re-indenting html or stripping tags to leave plain text.

Very long strings that need thousands of replacements are broken up into thousands of chunks and re-assembled once at the end, which makes this far more efficient than an "in situ" operation, since individual characters (in particular the last few) are moved just twice rather than thousands of times.

The Euphoria match_replace() routine offers similar but less efficient functionality, especially when the lengths of s and r differ. The previous replace_all() routine of Euphoria has been deprecated in favour of match_replace(). The Phix implementation of substitute() as found in builtins\substitute.e and reproduced below should work on Euphoria, once all the string types are replaced with sequence types.
Example:
?substitute("abracadabra", "ra", "X")       -- displays "abXcadabX"
?substitute("abracadabra", "a", "")         -- displays "brcdbr"
Implementation: See builtins\substitute.e (an autoinclude), reproduced in the technicalia dropdown below, for details of the actual implementation.
See Also: join, tagset
Expand/Shrink