This is an ancient question, but why is everyone overlooking the simplest regexp-based solution? Normal regexp quantifiers are greedy, people! If you want to find the last instance of a pattern, just stick .*
in front of it. Here's how:
$text = "The quick brown fox, fox, fox, fox, jumps over etc.";
$fixed = preg_replace("((.*)fox)", "$1DUCK", $text);
print($fixed);
This will replace the last instance of "fox" to "DUCK", like it's supposed to, and print:
The quick brown fox, fox, fox, DUCK, jumps over etc.