$str = 'blfoo and barthisfoothatqux and barsofooquxhim andfoosom foo'; # replace all foo(s) above with 123 except for the ones that are # surrounded by bar and qux # note: there are 5 foo(s) in $str above; only 3 should be replaced # so $str becomes # 'bl123 and barthisfoothatqux and barsofooquxhim and123som 123'