

In the second part, we are replacing the “Replace” of the input string with the ‘test’. In the first part of operation, we are replacing the string completely with the given string as we are specifying both starts as 0. Hence from the word “dress”, the first 2 letters will be replaced by “gu” hence becoming “guess”.Įxplanation: In this example, we are first declaring an input string $str upon which all the operations of the function are going to be performed. Example #5Įxplanation: In this example, we will specify the length parameter as 2 hence the substr_replace will start replacing the input string starting from the $start parameter which is 0 until 2. The second parameter “to” will be inserted at the position specified I.e, starting at 8th position.

Hence in this example, only the insertion takes place and there will be no replacement of strings as shown in the output.

Php substring first word how to#
Example #4Įxplanation: In this example, we are showing how to use the substr_replace to perform an insert since the replace parameter is set to 0. With the substr_replace function, we are replacing the word “Try” with the word “Done” in the starting first 3 positions. Example #3Įxplanation: In this example, we are replacing multiple strings declared inside the array at once. Hence this starts replacing the second parameter in place of first string from 3rd position starting the count from backward. This minus sign represents that the function should start replacing the word starting from the back. Example #2Įxplanation: In this example, we are showing the functionality of the -3 in the position parameter. Hence in the output exactly after 8th position the word “for” is replaced by “substring” word. Examples to Implement PHP substr_replace()īelow are the examples mentioned: Example #1Įxplanation: In this basic example, we can see that by using substr_replace function we are replacing the first string “Example for ” by the “substring” at the exact position given by the 3rd parameter i.e at the 8th position. If the case is of an array of strings, then the entire array is returned. Return Values: The value returned is the string that is generated after being replaced as per the above parameters.
