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:
Which prints out:@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";
To generalize this, you might want to use: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>.
which will ensure that your lists will replace the longest matches before the shortest.$swapString = join ("|", sort { length($b) <=> length($a) } @array, @a +rray2);
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |