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.

function str_replace_last( $search , $replace , $str ) {
    if( ( $pos = strrpos( $str , $search ) ) !== false ) {
        $search_length  = strlen( $search );
        $str    = substr_replace( $str , $replace , $pos , $search_length );
    }
    return $str;
}

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

    $str       = 'My Name is John.';
    $search    = 'John';
    $replace   = 'Peter';
    echo str_replace_last( $search , $replace , $str );
     
    //Result
    My Name is Peter.

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.