Coder Perfect

In a string, replace the final occurrence of a string.

Problem

Anyone know a quick way to replace a string’s last occurrence with another string in a string?

It’s worth noting that the string’s last occurrence may not be the string’s final characters.

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

Asked by Kirk Ouimet

Solution #1

You can make use of this feature by:

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

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

    return $subject;
}

Answered by Mischa

Solution #2

Another one-liner, but this time without the preg:

$subject = 'bourbon, scotch, beer';
$search = ',';
$replace = ', and';

echo strrev(implode(strrev($replace), explode(strrev($search), strrev($subject), 2))); //output: bourbon, scotch, and beer

Answered by ricka

Solution #3

$string = 'this is my world, not my world';
$find = 'world';
$replace = 'farm';
$result = preg_replace(strrev("/$find/"),strrev($replace),strrev($string),1);
echo strrev($result); //output: this is my world, not my farm

Answered by zack

Solution #4

The PCRE positive lookahead assertion is used in the following solution to match the last occurrence of the substring of interest, which is an occurrence of the substring that is not followed by any subsequent occurrences of the same substring. As a result, the last ‘fox’ in the example is replaced with ‘dog.’

$string = 'The quick brown fox, fox, fox jumps over the lazy fox!!!';
echo preg_replace('/(fox(?!.*fox))/', 'dog', $string);

OUTPUT: 

The quick brown fox, fox, fox jumps over the lazy dog!!!

Answered by John Sonderson

Solution #5

This is what you could do:

$str = 'Hello world';
$str = rtrim($str, 'world') . 'John';

‘Hello John’ is the result.

Answered by Nicolas Finelli

Post is based on https://stackoverflow.com/questions/3835636/replace-last-occurrence-of-a-string-in-a-string