in reply to Replacing a specfied instance of a pattern in a string
my $str = 'Fsih my test variable is fsihd or is it gfsih or gfsih +d fsih'; # 1111 2222 3333 + 4444 my $substr = 'fsih'; my $replace = 'fish'; my $instance = 3; # 3rd print("$str\n"); my $pos = -length($substr); for (;;) { last if !$instance--; $pos = index($str, $substr, $pos + length($substr)); last if $pos < 0; } substr($str, $pos, length($substr), $replace) if $pos >= 0; print("$str\n");
Update: Fixed off-by-one error.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Replacing a specfied instance of a pattern in a string
by Roy Johnson (Monsignor) on Jul 14, 2005 at 22:01 UTC | |
by ikegami (Patriarch) on Jul 14, 2005 at 22:48 UTC | |
Re^2: Replacing a specfied instance of a pattern in a string
by krisahoch (Deacon) on Jul 14, 2005 at 21:35 UTC | |
by ikegami (Patriarch) on Jul 14, 2005 at 21:36 UTC |
In Section
Seekers of Perl Wisdom