Forum Moderators: coopster

Message Too Old, No Replies

str replace - but just once

         

internetheaven

1:44 pm on Apr 10, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Seen a lot of lengthy code to replace only one instance in string e.g.

function str_replace_once($needle , $replace , $haystack){
// Looks for the first occurence of $needle in $haystack
// and replaces it with $replace.
$pos = strpos($haystack, $needle);
if ($pos === false) {
// Nothing found
return $haystack;
}
return substr_replace($haystack, $replace, $pos, strlen($needle));
}

any short versions? I have:

$show = str_replace('term','replacement',$string);

and read somewhere that there was a value you could enter to reduce the number of replacements to one i.e.

$show = str_replace('term','replacement',$string, 1);

rob7591

2:44 pm on Apr 10, 2009 (gmt 0)

10+ Year Member



The last line of code you tried is correct.
[us2.php.net...]

d40sithui

2:47 pm on Apr 10, 2009 (gmt 0)

10+ Year Member



Yep last line should do it, but only if you're running PHP 5 since the $count parameter was added after version 5.

internetheaven

5:13 pm on Apr 10, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I am running PHP 5 (5.2.9) and that line doesn't work though?

coopster

5:47 pm on Apr 10, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



The
count
argument is not a limit but count of the number of times the needle was found and replaced. To use a limit go with preg_replace [php.net].

internetheaven

6:19 pm on Apr 10, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks, but I'm not getting that working either. I tried:

$show = preg_replace('term','replacement',$string, 1);

and

$show = str_replace('term','replacement',$string[, 1]);

and neither of those two work.

coopster

6:27 pm on Apr 10, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



preg_replace requires a regular expression pattern as it's first argument and it must be in the proper syntax [php.net], meaning the expression must be enclosed in the delimiters.
print preg_replace("/ll/", "", "good golly miss molly!", 1); 
// good goy miss molly!

internetheaven

6:50 pm on Apr 10, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Of course it does! That's it, I'm going to bed ... ;)

Thanks everyone for your patience!