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
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.