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
Reference:
The substr_replace reference
Share "How to replace last occurrence of a string in a string in PHP?"
Related snippets:
- Remove whitespace from the beginning and end of a string in PHP
- Locate a substring within a string in PHP
- Process CSV line in PHP
- Extract a substring from a string in PHP
- Split a string into words in PHP
- Replace spaces with dashes in PHP
- Replace only the first occurrence of a string in PHP
- Replace last occurrence of a string in a string in PHP
- Remove all attributes from HTML tags in PHP
- Remove HTML tags from a string except p, b, i and br in PHP
- Remove HTML tags from a string in PHP
Tags:
replace, last, occurrence, match, string, text , php Technical term:
Replace last occurrence of a string in a string in PHP