views:

98

answers:

2

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

+5  A: 

You can use this function:

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

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

Source

captaintokyo
For safeties sake I'd add a check that `strrpos` doesn't return false, but otherwise OK.
Wrikken
Yeah, you are right. I will update my answer.
captaintokyo
A: 

This will also work:

function str_lreplace($search, $replace, $subject)
{
    return preg_replace('~(.*)' . preg_quote($search, '~') . '(.*?)~', '$1' . $replace . '$2', $subject, 1);
}

UPDATE Slightly more concise version (http://ideone.com/B8i4o):

function str_lreplace($search, $replace, $subject)
{
    return preg_replace('~(.*)' . preg_quote($search, '~') . '~', '$1' . $replace, $subject, 1);
}
Alix Axel
Am i doing it wrong ? If so just ignore me :) ||| echo str_lreplace("x", "y", "this x or that x"); => Output: "y" See: http://www.ideone.com/UXuTo
edorian
@edorian: Oops! Sorry, I posted that in a hurry, the correct version is here: http://ideone.com/vR073.
Alix Axel