I have to replace the last match of a string (for example the word foo) in HTML document. The problem is that the structure of the HTML document is always random.
I\
Of course the accepted solution given here is correct. Nevertheless you might also want to have a look at this post. I'm using this where no pattern is needed and the string does not contain characters that could not be captured by the functions used (i.e. multibyte ones). I also put an additional parameter for dis/regarding case.
The first line then is:
$pos = $case === true ? strripos($subject, $search) : strrpos($subject, $search);
I have to admit that I did not test the performance. However, I guess that preg_replace() is slower, specially on large strings.