I wanted a way to highlight search terms on the search results page (the way search engines do), by surrounding the text with <span class=whatever></span>, but simply doing preg_replace($re, '<span class=whatever>$0</span>', $text) replaces things inside any HTML tags as well. There are some solutions on the web, but the simplest one I found involves generating a new regular expression. I'd like something I can pass in the regular expression to match and the replacement text, something exactly equivalent to preg_replace.

What I came up with:

function preg_replace_text ($pattern, $replacement, $subject){
	// only replace text that is not inside tags. Assumes $subject is valid HTML and surrounded by tags
	// the (?<=>) is a lookbehind assertion to make sure the match starts with a >
	return preg_replace_callback('/(?<=>)[^<]*/', function($matches) use ($pattern, $replacement) {
		return preg_replace($pattern, $replacement, $matches[0]);
	}, $subject);

Hope this is useful to someone.

Leave a Reply

Warning: Undefined variable $user_ID in /home/public/blog/wp-content/themes/evanescence/comments.php on line 75