PHP str_replace_last function

I recently found myself in need of a way to replace the last (and only the last) occurrence of a substring within a string. Basically exactly str_replace, but only on the last occurrence of the needle within the haystack. I came up with this quick solution. Feedback welcome.

function str_replace_last( $search, $replace, $subject ) {
    if ( !$search || !$replace || !$subject )
        return false;
    
    $index = strrpos( $subject, $search );
    if ( $index === false )
        return $subject;
    
    // Grab everything before occurence
    $pre = substr( $subject, 0, $index );
    
    // Grab everything after occurence
    $post = substr( $subject, $index );
    
    // Do the string replacement
    $post = str_replace( $search, $replace, $post );
    
    // Recombine and return result
    return $pre . $post;
}

Hope someone else finds this useful.

This entry was posted in Code, php and tagged , . Bookmark the permalink.

2 Responses to PHP str_replace_last function

  1. Anonymous says:

    Very useful function. Thank you for sharing it :)

  2. You can simplify and optimize this by using substr_replace.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>