if you know roughly how close to the end of the string the substring that you want to replace is, you use substr_replace()
with a negative $start
and $length
parameters, or you could just code up a function by hand to actually go through, find the last occurrence, then delete it. something like this (untested, written very quickly):
function replace_last_occurrence($haystack, $needle) {
$pos = 0;
$last = 0;
while($pos !== false) {
$pos = strpos($haystack, $needle, $pos);
$last = $pos;
}
substr_replace($haystack, "", $last, strlen($needle));
}
similar, for first occurrence
function replace_first_occurrence($haystack, $needle) {
substr_replace($haystack, "", strpos($haystack, $needle, $pos),
strlen($needle));
}
you could also generalize this to replace the nth occurrence:
function replace_nth_occurrence($haystack, $needle, $n) {
$pos = 0;
$last = 0;
for($i = 0 ; $i <= $n ; $i++) {
$pos = strpos($haystack, $needle, $pos);
$last = $pos;
}
substr_replace($haystack, "", $last, strlen($needle));
}