#!/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;
<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>
(blew some whitespace in)

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)


In reply to Re: Regex to "wrap" a <span around an image. by wfsp
in thread Regex to "wrap" a <span around an image. by ultranerds

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.