$regex = join("|", map(quotemeta, sort { length $b <=> length $a } keys %hash)); s/($regex)/$hash{$1}/eg;