Given an HTML::Element, some match text and a formatting tag this code runs through and wraps matching text in the given formatting tags.

For example:

use strict; use warnings; use HTML::TreeBuilder; my $root = HTML::TreeBuilder->new (); $root->parse_file (*DATA); formatText ($root, 'bold', 'b'); formatText ($root, 'wrap selected text in formatting', 'i'); print $root->as_HTML(); __DATA__ <p>This test script demonstrates a way to run through the <em>text</em +> in a chunk of HTML and wrap selected text in formatting tags. </p> <p>Note that the text to be formatted must not contain any tags in the + original or the text will not match and that no checks are made for silly nesti +ng of formatting - re-formatting bold text won't make it double <i>bold</i> +but will double the bold tags.</p>

Prints

<html><head></head><body><p>This test script demonstrates a way to run + through the <em>text</em> in a chunk of HTML and <i>wrap selected te +xt in formatting</i> tags. <p>Note that the text to be formatted must + not contain any tags in the original or the text will not match and +that no checks are made for silly nesting of formatting - re-formatti +ng <b>bold</b> text won't make it double <i><b>bold</b></i> but will +double the <b>bold</b> tags.</body></html>
sub formatText { my ($node, $target, $tag) = @_; my @children = $node->detach_content (); my @newChildren; for (@children) { if (ref) { formatText ($_, $target, $tag); push @newChildren, $_; next; } my @fragments = split /($target)/, $_; while (@fragments) { push @newChildren, shift @fragments; last if ! @fragments; my $element = HTML::Element->new ($tag); $element->push_content (shift @fragments); push @newChildren, $element; } } $node->push_content (@newChildren) if @newChildren; }