in reply to Regex to "wrap" a <span around an image.
#!/usr/bin/perl use warnings; use strict; #use lib q{c:/www/lib}; #use SW::Debug; use HTML::TreeBuilder; my $html = <<HTML; <a href="page.html"> <img src="pic.jpg"> </a> <span>other stuff</span> <img alt="pic" width="10" height="10" src="pic.jpg"> <span>more</span> HTML my $tb = HTML::TreeBuilder->new_from_content($html); my @images = $tb->look_down(_tag => q{img}) or die qq{look_down for im +g failed: $!\n}; for my $img (@images){ $img->replace_with([q{span}, {id => q{fo_big}}, $img]); } print $tb->as_HTML;
(blew some whitespace in)<html> <head> </head> <body> <a href="page.html"> <span id="fo_big"> <img src="pic.jpg" /> </span> </a> <span>other stuff</span> <span id="fo_big"> <img alt="pic" height="10" src="pic.jpg" width="10" /> </span> <span>more</span> </body> </html>
The html and body tags are added by HTML::TreeBuilder. If you parse an HTML file they'll already be there.
update: commented out a stray "helper" module (not used by the code)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Regex to "wrap" a <span around an image.
by ultranerds (Hermit) on Nov 27, 2008 at 15:01 UTC |