in reply to Regex not working

When I saw this question my first reaction was the usual "just use a parser", so I thought I'd knock up something using HTML::Parser. That brought up some problems that I don't think can properly be solved using regular expressions, especially, what do you do if there are nested font tags as can happen (this is what I have the $font++ and $font-- for below).

So this bit of code is a bit longer than I expected but now that I've done it I might as well post. Note it only replaces font tags that have a color attribute, everything else is left as is.

use HTML::Parser (); my $parser = HTML::Parser->new( api_version => 3, start_h => [\&start_tag, "tagname, attr, text"], text_h => [\&text_content, "text"], end_h => [\&end_tag, "tagname, text"], ); my ( $font, %colored ); sub start_tag { my ($tagname, $attr, $text) = @_; if ($tagname eq 'font') { $font++; if (my $color = $attr->{'color'}) { print "[color=$color]"; $colored{$font}++; return; } } print $text; } sub text_content { my $text = shift; print $text; } sub end_tag { my ($tagname, $text) = @_; if ($tagname ne 'font') { print $text; return; } if ($colored{$font}) { print "[/color]"; } else { print $text; } $font--; } my $html1 = q|<font color="blue"><i><b> <br>Some text</font>, <br>an +a|; $parser->parse($html1); $parser->eof; print "\n\n"; my $html2 = q|<font color="blue"><i><b> <font>breaker</font><br><font +color="#ff0000">Some</font> text</font>, <br>an a|; $parser->parse($html2); $parser->eof;
Output:
[color=blue]<i><b> <br>Some text[/color], <br>an a [color=blue]<i><b> <font>breaker</font><br>[color=#ff0000]Some[/color] + text[/color], <br>an a