Search & replace with regular expressions

pax_grep is a plugin for Textpattern that allows you to find occurrences of a regular expression pattern and replace them with something else. It’s almost identical to it’s awesome parent plugin rah_replace by Jukka Svahn. pax_grep uses PHP’s preg_replace() function, packaged in a compact and easy-to-use Textpattern tag.

Installaing/Uninstalling

In Textpattern, navigate to the “Plugins” tab under “Admin”, and paste the code into the “Install plugin” pane. Install and enable the plugin.

To uninstall, simply delete the plugin from the “Plugins” tab.

Usage

pax_grep takes a regular expression and searches content for matching patterns. Then it replaces matches with the string(s) you supply. This works just like rah_replace. If you don’t need to search and replace based on a regular expression, you should use rah_replace instead.

Syntax

pax_grep is a container tag with two attributes.

<txp:pax_grep ↩
	from="/search pattern/" ↩
	to="replacement text">
	Content
</txp:pax_grep>

Attributes

from

Give this attribute the value of a pattern or patterns you wish to search for. A pattern should be delimited with single quotes or some other character not used in the pattern. Separate multiple patterns with commas.

Default: from=""
Example: from="'^foo','bar$'"

to

This attribute holds the replacement value(s) for each pattern in the from attribute. No delimiters are needed, but multiple values must be separated by commas. Each from value will be replaced with the corresponding to value.

Default: to=""
Example: to="fox,bat"

Examples

Replace all vowels with hyphens.

This example searches for the any vowel, replacing each one with a hyphen.

<txp:pax_grep from="'[aeiou]'" to="-">
	My favorite animal is a dog.
</txp:pax_grep>
Result: M- f-v-r-t- -n-m-l -s – d-g.

Get words out of a request_uri.

This example outputs the current request URI, and uses a regular expression to drop the leading slash and transform many delimiter characters into spaces.

<txp:pax_grep ↩
	from="'^\/','\/','%20','\-','\+','\?=','\_'" ↩
	to=", , , , , , ">
	<txp:page_url type="request_uri" />
</txp:pax_grep>

If the browser is pointed to example.com/section-name/my-article-title/, pax_grep will return the following:

section name my article title

Changelog

Version 0.1.1

  • 2009-01-25: Changed plugin name from opus_grep to pax_grep in compliance with defacto standard of three-letter prefix for plugins.

Version 0.1

  • 2009-01-23: Branched from rah_replace by Jukka Svahn— changed str_replace() to preg_replace().

Project Type

A plugin for the Textpattern CMS

Previous
Next
Completed
Jan 2009
Topics
  • content management
  • plugin
  • textpattern

Design Opus: Creative, professional web design and development in Harrisonburg, Virginia

Web craftsman
John Stephens
Location
  1. Harrisonburg, VA
  2. 22802 USA
Phone
(703) 634-9373
Tags
Top