UPDATE: OK, here's something that will break. Let's say there's a comment in your html and the comment has a < or >. This will confuse your parser, because it doesn't check for comments:
So, do like grandfather says and use Treebuilder or one of the HTML::Parser family of modules.
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $html = ''; while (<DATA>) { $html .= $_; } my $begin = 0; my $end = 0; my @excerpts = (); for (my $i=0;$i<length($html);$i++) { if (substr($html,$i,1) eq '>') { $begin = $i + 1; } if ($begin && substr($html,$i,1) eq '<') { $end = $i; } if ($begin && $end) { push @excerpts, { begin => $begin, end => $end }; $begin = 0; $end = 0; } } # last snippet if ($begin && !$end) { push @excerpts, { begin => $begin, end => length($html) }; } my @word_pos_list = (); foreach my $excerpt (@excerpts) { my $begin = $excerpt->{begin}; my $end = $excerpt->{end}; my $length = $end - $begin; my $word_string = substr($html,$begin,$length); while ($word_string =~ m/(\b\w+\b)/g) { my $word_begin = $begin + $-[0]; my $word_end = $begin + $+[0]; my $word_length = $word_end - $word_begin; push @word_pos_list, { begin => $word_begin, end => $w +ord_end, length => $word_length, word => $1 }; } } print "Original HTML:\n"; print "$html\n"; print "**************************************\n"; print "New HTML:\n"; my $test_repl = $word_pos_list[6]; my $repl_beg = $test_repl->{begin}; my $repl_length = $test_repl->{length}; substr($html,$repl_beg,$repl_length,'POOP'); print $html; __DATA__ <HTML> <body poop=smelly> <p> This is my text. I <b>hope</b> you like it! <table> <!-- < --> <tr> <td> Would you like to see my Monkey? </td> </tr> </table> </body> oh and this too!
In reply to Re^2: regex for search and replace of words in HTML
by tphyahoo
in thread regex for search and replace of words in HTML
by jqcoffey
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |