Replace last occurrence of a string in a string

Kirk Ouimet picture Kirk Ouimet · Oct 1, 2010 · Viewed 108.1k times · Source

Anyone know of a very fast way to replace the last occurrence of a string with another string in a string?

Note, the last occurrence of the string might not be the last characters in the string.

Example:

$search = 'The';
$replace = 'A';
$subject = 'The Quick Brown Fox Jumps Over The Lazy Dog';

Expected Output:

The Quick Brown Fox Jumps Over A Lazy Dog

Answer

Mischa picture Mischa · Oct 1, 2010

You can use this function:

function str_lreplace($search, $replace, $subject)
{
    $pos = strrpos($subject, $search);

    if($pos !== false)
    {
        $subject = substr_replace($subject, $replace, $pos, strlen($search));
    }

    return $subject;
}