http://www.perlmonks.org?node_id=206197

Parham has asked for the wisdom of the Perl Monks concerning the following question:

Someone came to me with a PHP question, I used perl to solve it :P. This was what the person wanted:
<tag#1>BLA</tag#1><tag#2>BLA</tag#1><tag#3>BLA</tag#1>
to turn into:
<tag#1>BLA</tag#1><tag#2>BLA</tag#2><tag#3>BLA</tag#3>
meaning the first tag opened had to be the first tag closed. There was a trick to this question though. The person wanted the finishing tag to be the first paramater in the html tag. So if i had < font size=2 > I would have to end it with < /size > and not < /font >. My first instinct was to do a while loop through the tags, find what i needed, do a replace, and continue:
$text = "<tag#1>BLA</tag#2><tag#2>BLA</tag#2><tag#3>BLA</tag#3>"; $number = 1; while ($text =~ s/<(.+?)#\d>(.+?)<\/(.+?)#\d>/<$1#$number>$2<\/$3#$num +ber>/) { $number++; last; } print "$text\n";
Now I couldn't even answer it, but the process would only work with one loop, thus the "last;" (I guess I didn't need to increment $number then :P). Anyway, that solution partially worked. So i tried again:
$text = "<FONT face=arial>this is <FONT SIZE=2>TWO</FONT>bla<FONT colo +r=red>red</FONT>bla bla</FONT>"; $text =~ s#<(.+?\s(.+?)=.+?)>(.+?)<\/.+?>#<$1>$3<\/$2>#g; print "$text\n";
which also partially worked. Although the problem is long past, the situation still creeps in my head. This is all old code, but the question has bothered me for a while. The only real reason I'm asking is because I want to gain some valuable experience from it. So I'm just wondering if anyone has a better solution than the two I provided above? Seeking the wisdom of the perlmonks :)

Edit: Added some <code> tags. larsen