$text = "BLABLABLA"; $number = 1; while ($text =~ s/<(.+?)#\d>(.+?)<\/(.+?)#\d>/<$1#$number>$2<\/$3#$number>/) { $number++; last; } print "$text\n";