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__

This test script demonstrates a way to run through the text in a chunk of HTML and wrap selected text in formatting tags.

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-formatting bold text won't make it double bold but will double the bold tags.

####

This test script demonstrates a way to run through the text in a chunk of HTML and wrap selected text in formatting tags.

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-formatting bold text won't make it double bold but will double the bold tags. #### 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; }