Replace last occurrence of a string in a string
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
Solution 1:
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;
}
Solution 2:
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
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