my $foo = 'Fsih my test variable is fsihd or is it gfsih or gfsihd fsih'; my $from = 'fsih'; my $which = 3; my $to = 'FISH'; # makes it easy to see $foo =~ /\Q$from\E/ig for (1..$which); substr($foo, pos($foo) - length($from), length($from), $to) if pos($foo); print "Foo = $foo\n";