Page 1 of 1

the problem with str_replace

Posted: Mon Oct 26, 2009 2:00 am
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? :) :)

Re: the problem with str_replace

Posted: Mon Oct 26, 2009 2:04 am
by tsmg
I know the problem now,the $nn is the return value,not the control reference,my god.

Re: the problem with str_replace

Posted: Mon Oct 26, 2009 2:47 am
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.

Re: the problem with str_replace

Posted: Mon Oct 26, 2009 6:15 am
by tsmg
Thanks a lot!

preg_replace