the problem with str_replace

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tsmg
Forum Newbie
Posts: 7
Joined: Mon Oct 26, 2009 1:57 am

the problem with str_replace

Post by tsmg »

$str="hahahahahahahahahahahahahaha";
$nn=1;
$str=str_replace('ha','MyGod',$str,$nn);


echo $str;

the result is MyGodMyGodMyGodMyGodMyGodMyGodMyGodMyGodMyGodMyGodMyGodMyGodMyGodMyGod

Why $nn has no effect?the version of my php? :) :)
tsmg
Forum Newbie
Posts: 7
Joined: Mon Oct 26, 2009 1:57 am

Re: the problem with str_replace

Post by tsmg »

I know the problem now,the $nn is the return value,not the control reference,my god.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: the problem with str_replace

Post by requinix »

One solution is preg_replace (which can have a limit on the number of replacements) but if all you want is to replace the first instance some work with strpos and substr is better.
tsmg
Forum Newbie
Posts: 7
Joined: Mon Oct 26, 2009 1:57 am

Re: the problem with str_replace

Post by tsmg »

Thanks a lot!

preg_replace
Post Reply