PHP – Replace Last Occurrence of a String

The below code example shows you the way to replace the last occurrence of a string in PHP.
 

1. Implementation

StringExample.php
function replaceLast($find, $replace, $string) {
    $lastIndex = strrpos($string, $find);
    
    if ($lastIndex === false) {
        return $string;
    }
    
    return substr_replace($string, $replace, $lastIndex, strlen($find));
}

 

2. Usage

The below are two examples showing how to use the function.

  • Example 1:
$str1 = 'Hello World-';
$newStr1 = replaceLast("-", "", $str1);
echo $newStr1;

 

  • Output 1:
Hello World

 

  • Example 2:
$str2 = 'Foo and Bar. Hello Bar';
$newStr2 = replaceLast("Bar", "guys", $str2);
echo $newStr2;

 

  • Output 2:
Foo and Bar. Hello guys

0 0 vote
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x