Replace last occurrence of a substring in a string in PHP
This article demonstrates how to replace the last occurrence of a substring in a string in PHP.
1. Using substr_replace() function
You can use the substr_replace() function to replace text within a portion of a string. It takes four parameters: the input string, the replacement string, the offset position, and optionally the length, in that order. The offset indicates where replacing will begin in the string.
The following solution replaces the last occurrence of a substring within the source string using the substr_replace() function. It uses the strrpos() function to determine the position of the substring’s last occurrence in a string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php function right_replace($string, $search, $replace) { $offset = strrpos($string, $search); if ($offset !== false) { $length = strlen($search); $string = substr_replace($string, $replace, $offset, $length); } return $string; } $string = 'A program in PHP programming language'; $search = 'program'; $replace = '*******'; $str = right_replace($string, $search, $replace); echo $str; /* Output: A program in PHP *******ming language */ ?> |
2. Using preg_replace() function
Another option is to use the preg_replace() function to replace the last occurrence of a substring in a string. It uses a regex for searching and replacing, but at the cost of performance. To replace the last occurrence of the substring within the string, you can use the positive lookahead assertion to match the last occurrence, as demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php function right_replace($string, $search, $replace) { return preg_replace("/($search(?!.*$search))/", $replace, $string); } $string = 'A program in PHP programming language'; $search = 'program'; $replace = '*******'; $str = right_replace($string, $search, $replace); echo $str; /* Output: A program in PHP *******ming language */ ?> |
That’s all about replacing the last occurrence of a substring in a string in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)