i have
$str ="GOODDAY"
and i need to replace O with U , but not change ALL O characters.
For example
$str1 ="GUODDAY" ; $str2 ="GOUDDAY" ; $str3 ="GUUDDAY" ;
i used str_replace but only get $str3 , any idea?
Advertisement
Answer
It looks like you want to print the string as many times as the occurrences of O, and replace O once each time, according to the iteration number, and finally print the string with all O replaced. This will do it:
$str = "GOODDAY";
$find = "O";
$replaceWith = "U";
$lastPos = 0;
while (($lastPos = strpos($str, $find, $lastPos)) !== false) {
    echo substr_replace($str, $replaceWith, $lastPos, 1) . "n";
    $lastPos = $lastPos + strlen($find);
}
echo str_replace($find, $replaceWith, $str);