This article demonstrates how to replace the first occurrence of a substring in a string in PHP.

1. Using implode()/explode() function

You can replace the first occurrence of a substring using the implode() and explode() functions. The idea is to divide the string into two strings: one that contains all characters before the searched string, and one that contains all characters after the searched string. Finally, join both strings and return them.

The following code uses the limit parameter of the explode() to restrict the replacement to the first occurrence only. You can skip the limit parameter to replace all occurrences of the substring.

Download  Run Code

2. Using substr_replace() function

You can use the substr_replace() function to replace text within a portion of a string. It takes four parameters, in that order: the input string, the replacement string, the offset position, and optionally the length. The following solution replaces the first occurrence of a searched string in the given string using the str_replace() function. It uses strpos() function to determine the position of the first occurrence of the substring in a string.

Download  Run Code

 
As a bonus, here’s the PHP equivalent of Java’s removeCharAt() function that can be implemented with substr_replace() function:

Download  Run Code

3. Using preg_replace() function

Alternatively, you can replace the first occurrence of a substring in a string using the preg_replace() function. The preg_replace() function uses a regular expression for search and replace. The following code replaces the first occurrence of a substring within a string using preg_replace(). It uses limit = 1 (the fourth parameter) to restrict the maximum possible replacements for the specified pattern to the first occurrence. You can skip the limit parameter to replace all occurrences of the substring within the string.

Download  Run Code

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