$x =~ s{(?<=) # Start match with open-tag ( # Capture (?:(?!).)* # Any number of characters that do not start an open-tag )3 # Close capture; match literal 3 (?= # Look ahead to match (?:(?!).)* # Any number of characters that do not start a close-tag # then a close-tag )} # End lookahead and pattern {$1a}x;