Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

search and replace the second occurrence

Status
Not open for further replies.

jr8rdt

IS-IT--Management
Feb 9, 2006
59
0
0
US
Hi ,
how can I search and replace the second (or n) occurrence ?

this will replace ALL $b with $c

$a =~ s/$b/$c/g;

I just want to replace the 2nd $b with $c

Thanks
 
This may not be the most elegant, but should get you pretty close
Code:
$str = 'abc123abc456' ;
$b = 'abc';
$c = 'xyz' ;
$str =~ s/(.*?$b)(.*?)$b(.*)/$1$2$c$3/ ;
 
Simpler and faster by 17% to 20% (longer strings will get a better % rate). Good call.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top