my $text = "blah blah [click me](click me) more stuff\nblah [link here](link here) blah blah"; $text =~ s/(\[[^]]+]\()/$1\//g; # make links absolute my @matches = $text =~ /(\[[^]]+]\(\/)([^\)]+)/g; while (@matches) { my $part1 = shift @matches; my $part2 = shift @matches; my $orig_part2 = $part2; $part2 =~ s/ /-/g; $text =~ s/\Q$part1$orig_part2\E/$part1$part2/g; }