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

In reply to Re: Regex not working by tangent
in thread Regex not working by Beaker

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.