How to replace only the last match of a string with preg_replace?

后端 未结 4 1172
时光取名叫无心
时光取名叫无心 2020-12-17 00:17

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\

4条回答
  •  情深已故
    2020-12-17 01:11

    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.

提交回复
热议问题