[Solved] how to search and replace specific src=”url” tag in html using perl?


First of all, we need to distill your problem down to the part we actually care about. Your example code is not great because it contains a lot of unrelated errors, so I’ve taken some liberties in stripping out stuff I didn’t feel was absolutely necessary to solve the problem. I also added some line breaks to your HTML to help with the horizontal scrolling.

That leaves us with this:

use strict;
use warnings;

use HTML::TokeParser::Simple;

my $bunchotxt = << 'END_MESSAGE';
<a href="http://link.com/image.gif">
  <img
      class="alignleft size-thumbnail wp-image-295"
      src="http://link.com/image.gif"
      alt="shredding"
      width="150"
      height="150" />
</a>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis convallis
fringilla dui eget cursus. Nullam in mauris viverra elit pharetra fringilla.
Pellentesque gravida ligula sit amet magna blandit, semper luctus enim semper.
Nam a sem ut ex aliquam consectetur. Nulla enim metus, porta at elementum non,
facilisis ullamcorper nisl. Vestibulum sed iaculis ante. Nullam mollis luctus
posuere.

Suspendisse ipsum odio, iaculis in malesuada id, varius
END_MESSAGE

my $parser = HTML::TokeParser::Simple->new(string => $bunchotxt);

while (my $tag = $parser->get_tag('img')) {
    my $src = $tag->get_attr('src');
    $bunchotxt =~ s/\Qsrc="$src"\E/src:"replaced"/g;
    print "$bunchotxt\n";
}

And the first line of the result is:

<a href="http://link.com/image.gif"><img class="alignleft size-thumbnail wp-image-295" src:"replaced" ...

2

solved how to search and replace specific src=”url” tag in html using perl?