- Instant help with your Php coding problems

Replace last occurrence of a string in a string in PHP

Question:
How to replace last occurrence of a string in a string in PHP?
Answer:
$originalText = 'asd 123 mnb ert 123 asd 123 mnb';

$lastPos = strrpos($originalText, '123');
if ($lastPos) {
    $newText = substr_replace($originalText, '888', $lastPos, strlen('123'));
    echo $newText . '<br/>';
}
Description:

Replacing the last occurrence of a string in another string is a bit more complex than simply replacing all occurrences. First, we need to find the position of the last occurrence with the strrrpos method and then replace part of the original string with a new string using the substr_replace method. 

Syntax:

substr_replace(
    array|string $string,
    array|string $replace,
    array|int $offset,
    array|int|null $length = null
): string|array
Share "How to replace last occurrence of a string in a string in PHP?"