Rah's Replace
A tiny Textpattern plugin that returns contained content with all searched occurrences replaced with given replacements. This ideally works in the same manner as PHP’s str_replace function, but with a Textpattern’s XML tag.
Version 0.4.2 May 07, 2013
Other versions...
A cup of coffee
via PayPal
Basics
The plugin, rah_replace, introduces a new container tag to Textpattern’s arsenal. The tag returns wrapped content with all found occurrences replaced with given replacements. A tag supports multiple searched occurrences and replacements.
<txp:rah_replace from="value1, value2, ..." to="value1, value2, ...">
Searched content
</txp:rah_replace>
Attributes
The tag is a container, <txp:rah_replace> ...contained statement... </txp:rah_replace>
, and attributes for it follow.
from
Strings that will be searched and replaced with to
attribute’s values. Separate multiple values with a comma (or delimiter
if changed).
Default: from=""
Example: "dog,cat,house"
to
Replacements that will be used to replace from
attribute’s values. Comma (or delimiter
) separated if multiple.
Default: to=""
Example: "ship,home,hat"
delimiter
Sets the delimiter used in from
and to
to separate multiple values. Default is a comma.
Default: delimiter=","
Example: "|"
Examples
Replaces a dog with a cat
<txp:rah_replace from="dog" to="cat">
My favorite animal is a dog.
</txp:rah_replace>
Returns: My favorite animal is a cat.
Replace multiple needles with different replacements
<txp:rah_replace from="house,dog,Mike" to="boat,friend,wife">
I live in a house with my dog and Mike.
</txp:rah_replace>
Returns: I live in a boat with my friend and wife.
Replace multiple needles with a one replacement
<txp:rah_replace from="Mike,dad" to="I">
I remember when dad and Mike did go to fishing.
</txp:rah_replace>
Returns: I remember when I and I did go to fishing.
Using a different delimiter
By default any comma is treated as a delimiter and can not be used as actual value. To use a comma (,
) as a needle or a replacement, you would have to change the delimiter to something else. Like for instance to a vertical bar:
<txp:rah_replace from=".|," to="!" delimiter="|">
A, B, C.
</txp:rah_replace>
Returns: A! B! C!
Changelog
Version 0.4.2 – 2013/05/07
- The Composer package uses textpattern/installer and textpattern/lock.
Version 0.4.1 – 2013/04/25
- Minor clean up.
- Released as a Composer package.
Version 0.4 – 2012/07/12
- Performance optimization.
Version 0.3 – 2011/04/22
- Performance optimization.
Version 0.2 – 2009/04/16
- Added a new attribute:
delimiter
.
Version 0.1 – 2009/04/16
- Initial release.