Replace last occurrence of a String – PHP

Replacing part of a string with another string is straight forward, but what if you have to replace last occurrence of a character or string with another string.

Here is the fastest way to do this.

The first argument $search keeps the string to be searched for, $replace is the replacement string and $str is the subject string, commonly known as haystack.

How to replace last occurrence of a string

In case the $search is not found inside the $str, the function returns the original untouched string $str. This behavior is compatible with the default behavior of str_replace PHP’s builtin function that replaces all occurrances of a string inside another string.