$n=2; # x-1 $chr="e"; $rep="1"; $a="Terence and Philip are sweet"; while ($a=~s/^((?:.*?$chr){$n})(.*?)$chr/$1$2$rep/) {} #### 1 while ($a=~s/^((?:.*?$chr){$n})(.*?)$chr/$1$2$rep/);