How to String Replace Last Occurrence in PHP?

03-Apr-2023

.

Admin

How to String Replace Last Occurrence in PHP?

Hi Dev,

This post will give you example of how to string replace last occurrence in PHP. In this article, we will implement a replace last occurrence of a string. This post will give you simple example of substr_replace function using PHP. I would like to share with you replace just the last match of a string. you will do the following things for PHP Replace last occurrence of a word in string.

To replace the last occurrence of a substring within a string in PHP we will use the substr_replace() functions and Use the str_replace() function to perform a simple string replacement. Here’s how to replace summer with winter in a string taken.

Example: 1


index.php

<?php

$searchFor = 'hello';

$replaceWith = 'lets learn!';

$mainString = 'hello from nicesnippets hello';

$stringPosition = strrpos($mainString, $searchFor);

$newString = substr_replace($mainString, $replaceWith, $stringPosition, strlen($searchFor));

echo $newString;

?>

Output:

hello from nicesnippets lets learn!

Example: 2

index.php

<?php

$string = "It's summer season!";

print(str_replace("summer", "winter", $string));

?>

Output:

It's winter season!

I hope it could help you...

#PHP