Finding and Replacing the First or Last Substring in a String

search-replace-graphicI found this image on using Google Image search.

Today, I found myself in a position where I needed to find a substring within a larger string and then replace the last occurrence of that substring. I started out using the str_ireplace function, but quickly realized there was no way to add an offset or a limit to that function. I then started searching the Internet for a solution. I came across a handful of places where someone had asked to replace the first instance of the substring, but all of the answers seemed to recommend using the preg_replace function (which allows you to set a limit).

With no good answer, I decided to set out and build my own function to do this. I have not tested the performance of this function to determine whether it’s slower or faster than using preg_replace, but I would imagine it’s probably faster (I’d love for someone to benchmark the comparison using a variety of string lengths to find out for sure, though).