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.
2 Responses to PHP str_replace_last function