If all you're trying to do is replace a series of words, some of which are substrings of other words in the series, there is a simpler way--

You could simply have your replacing regexp do all of the replacing at once. Regexp 'or' matches try to match the leftmost string first, so you could simply combine your two lists as such:

@array = ( "foo bar", "bar foo" ); @array2 = ( "foo", "bar" ); $string = "there is a foo bar and a bar foo and also foo and bar."; print "string before - $string\n"; $swapString = join ("|", @array, @array2); print "swapString 1 - $swapString\n"; $string =~ s/($swapString)/<B>$1<\/B>/gi; print "string after first - $string\n";
Which prints out:
string before - there is a foo bar and a bar foo and also foo and bar. swapString 1 - foo bar|bar foo|foo|bar string after first - there is a <B>foo bar</B> and a <B>bar foo</B> an +d also <B>foo</B> and <B>bar</B>.
To generalize this, you might want to use:
$swapString = join ("|", sort { length($b) <=> length($a) } @array, @a +rray2);
which will ensure that your lists will replace the longest matches before the shortest.

If there's some other reason for needing to do this in two passes, disregard this solution.

stephen


In reply to Re: Double regex match not working correctly. by stephen
in thread Double regex match not working correctly. by the_0ne

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.