Replace last occurrence of a string in a string Replace last occurrence of a string in a string php php

Replace last occurrence of a string in a string


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;}


Another 1-liner but without preg:

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


$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