Page 1 of 1
How to replace one occurrence of a word with PHP
Posted: Tue Jan 17, 2012 10:26 am
by lovelf
example: $var1='hellowordinghellowording';
I want to replace hello just once not twice inside this variable
Re: How to replace one occurrence of a word with PHP
Posted: Tue Jan 17, 2012 10:36 am
by lovelf
Code: Select all
function str_replace_once($str_pattern, $str_replacement, $string){
if (strpos($string, $str_pattern) !== false){
$occurrence = strpos($string, $str_pattern);
return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern));
}
return $string;
}
I have that function to replace once, now what to replace more than once, a given number of times, taken by the count parameter of the str_replace function, to replace all occurrences but one.
Re: How to replace one occurrence of a word with PHP
Posted: Tue Jan 17, 2012 10:43 am
by lovelf
Got it, with a loop