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.

Download  Run Code

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:

Download  Run Code

That’s all about replacing the last occurrence of a substring in a string in PHP.