$string =~ s/[^]($swapString)[^<\/B>]/$1<\/B>/gi; #### [^] <- this matches any *single* char that is not a < B > ($swapString) <- this put the match for $swapstring into $1 [^<\/B>] <- this matches any *single* char that is not a < / B > #### $string =~ s/([^]($swapString)[^<\/B>])/$1<\/B>/gi; there is a foo bar and a bar foo and also foo and bar. #### $string =~ s/(?)($swapString)(?!<\/B>)/$1<\/B>/gi; # this gives: there is a foo bar and a bar foo and also foo and bar.