in reply to Re^2: regex for search and replace of words in HTML
in thread regex for search and replace of words in HTML
You might like this:
use strict; use warnings; use HTML::TreeBuilder; my $html; $html .= $_ while <DATA>; my $Tree = HTML::TreeBuilder->new (); $Tree->parse ($html); $Tree->eof (); my %Words; ++$Words{$_} foreach (split (" ", $Tree->as_text ())); my @WordPos; my $Key; foreach $Key (keys %Words) { pos ($html) = 0; while ($html =~ />[^<]*?(\b$Key\b).*?[<\$]/gis) { push @WordPos, [$Key, $-[1]]; } } print join "\n", map {ref $_ ? join ' starts at ', @$_ : $_} @WordPos; __DATA__ <HTML> <body poop=smelly> <img src="PleaseDon'tMuntMe.gif"/> <p> This is my text. I <b>hope</b> you like it! img src, please don't munt me. <table> <tr> <td> Would you like to see my Monkey? </td> </tr> </table> </body> oh and this too!
don't starts at 126 you starts at 97 you starts at 182 img starts at 110 hope starts at 88 my starts at 73 my starts at 198 is starts at 70 This starts at 65 see starts at 194 munt starts at 132 like starts at 101 like starts at 186 to starts at 191 Monkey? starts at 201 this starts at 65 Would starts at 176 please starts at 119 I starts at 83
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: regex for search and replace of words in HTML
by jqcoffey (Novice) on Jun 16, 2005 at 22:13 UTC |