johannz has asked for the wisdom of the Perl Monks concerning the following question:
I am filtering HTML pages and would like to bold every mention of the term 'Perl' in the body. Currently, I am doing this with the HTML::TreeBuilder module, as the following code demonstrates.
My question is: Is this the most effective/safest way to do this?
FYI, this code is actually being used in a HTML::Mason autohandler, in the filter section. In the real code, I put the return value back into $_, as required by Mason. Therefore, I can not use print statements or any other direct output from my process. This also ensures that I only change instances of perl that are text, not included in links, images, or other tags.
#! perl use strict; use warnings; use HTML::TreeBuilder; use HTML::AsSubs; undef $/; print processHTML(<DATA>); exit; sub processHTML { my $tree = HTML::TreeBuilder->new_from_content($_[0]); $tree->elementify(); my @body = $tree->look_down("_tag", "body"); for my $body (@body) { $body->objectify_text(); my @perl_parts = $body->look_down("_tag", "~text", sub {$_[0]->attr('text') =~ /perl/i} ); for my $perl_text ( @perl_parts ) { my @items = split(/(perl)/i, $perl_text->attr('text')); $_ = (/perl/i ? b($_) : $_) for @items ; $perl_text->replace_with(@items)->delete(); } $body->deobjectify_text(); } my $return = $tree->as_HTML; $tree->delete; $return; } __END__ <html> <head> <title>This title contains Perl but does not get changed.</title> </head> <body> <p>This is some text containing the term 'perl'.</p> <ol> <li>Unix</li> <li>Perl</li> <li>Linux</li> </ol> <p>Notice how the term perl in the following link doesn't change, but +the text does. <a href="http://www.perlmonks.org">Perlmonks.org</a></p> </body> </html>
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
(crazyinsomniac) Re: Is this the best way to use HTML::TreeBuilder to bold text in an HTML document?
by crazyinsomniac (Prior) on Feb 02, 2002 at 02:13 UTC | |
|
Re: Is this the best way to use HTML::TreeBuilder to bold text in an HTML document?
by gav^ (Curate) on Feb 02, 2002 at 03:06 UTC | |
|
Re: Is this the best way to use HTML::TreeBuilder to bold text in an HTML document?
by trs80 (Priest) on Feb 02, 2002 at 02:16 UTC |