Have you considered that maybe you are doing this the hard way? At the very least HTML::Strip may make your life easier without having to make highly complex regexen.

Update never mind...
I just realized you are adding the span tags yourself, so you probably want them to stay. Have you considered just marking all the text positions you need and then going by from the right hand side of the string back putting in your tags. This is pretty simple unless you have overlaps, and even then you could do it easier.

For instance, keep a list of tags and their positions in the original string, storing the start and end tags, then strip off everything in the original string until the next tag, print the string, than print any tags that belong at that position, and go to the next position... FAR easier than re-iterating over and over again...

Here is an example

$_ = 'TTTDDDTTTTTTX'; my @patterns = qw(TTT DDD TD TTTTTT); my %tags; for my $pat (@patterns) { while(/($pat)/g) { print "$pat = $-[0] $+[0]\n"; push @{$tags{$-[0]}}, "<SPAN CLASS=$pat>"; push @{$tags{$+[0]}}, "</SPAN>"; } } my $currentpos = 0; print "$_\n"; for my $pos (sort { $a <=> $b } keys %tags) { print substr($_,0,($pos-$currentpos),''); print join('',@{$tags{$pos}}); $currentpos = $pos; } print $_,"\n";

                - Ant
                - Some of my best work - (1 2 3)


In reply to Re: s/// only replacing most of the time... by suaveant
in thread s/// only replacing most of the time... by mdunnbass

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.