PHP substr_replace() Function (original) (raw)

Last Updated : 11 Jul, 2025

The substr_replace() function is a built-in function in PHP and is used to replace a part of a string with another string. The index in the original string from which the replacement is to be performed needs to be passed as a parameter. If desired, the length up to which the replacement is to be done can also be specified. An array of strings can be provided as a parameter to this function, in which case the replacements will occur on each string in turn. Syntax :

substr_replace($string, replacement,replacement, replacement,start, $length)

Parameters: This function accepts four parameters as shown in the above syntax out of which first three are mandatory and the last one is optional. All of these parameters are described below:

Return Value: The string generated after replacement is returned. In case of an array of strings, the array is returned. Examples:

Input : string="GeeksforGeeks",string = "Geeks for Geeks", string="GeeksforGeeks",replacement = "GFG", $start = 0 Output : GFG

Input : string="HelloWorld",string = "Hello World", string="HelloWorld",replacement = "Hello", $start = 6 Output : Hello Hello

Below programs illustrate the substr_replace() function: Program 1: In this program we will use the substr_replace() function without any lengthparameter.Allthecharactersfromlength parameter. All the characters from lengthparameter.Allthecharactersfromstart to the end of stringwillgetreplacedbystring will get replaced by stringwillgetreplacedbyreplacement.

php `

`

Output

Hello GFG

Program 2: In this program we will use the substr_replace() function with $length set to 0. In this case, insertion will occur. No replacement will take place.

php `

`

Output

Contribute to GFG

Program 3: In this program we will use the substr_replace() function with lengthsettoapositivevalue.Inthiscase,thelength set to a positive value. In this case, the lengthsettoapositivevalue.Inthiscase,thereplacement string will replace characters of stringuptostring up to stringuptolength from $start.

php `

`

Output

phone

Program 4: In this program we will use the substr_replace() function with lengthsettoanegativevalue.Inthiscase,thelength set to a negative value. In this case, the lengthsettoanegativevalue.Inthiscase,thereplacement string will replace characters of stringfromstring from stringfromstart and stop before $length number of characters from the end of the string .

php `

`

Output

phone

Program 5: In this program we will use the substr_replace() function without any lengthparameterandlength parameter and lengthparameterandstart set to a negative value. The replacement will start at the specified position from the end of the string.

php `

`

Output

alone

Reference : https://www.php.net/manual/en/function.substr-replace.php