PHP String substr_replace() FunctionThe substr_replace is an in-built function of PHP, which replaces a part of the string with another text within a string. PHP 4+ versions support this function. The index in the original string is passed as a parameter to which the replacement is to be performed. An array of string can also be passed as a parameter to this function, and in that case, a replacement will be done for each string at every turn (See Example 5). Note: The substr_replace() is a binary-safe function.SyntaxThe syntax for the substr_replace() is given below, which accepts four arguments. ParametersThe substr_replace() consists of four parameters, in which three parameters are mandatory to pass in this function whereas $length parameter is optional. All these parameters are discussed below in detail: $string (required) - It is the main string parameter of this function, which specifies the input string in which the replacement will be done. This is a mandatory parameter. $replacement (required) - It is a mandatory parameter of the substr_replace(), which specifies the string to insert. The $replacement contains the string to which the replacement is going to be done. $start (required) - It is also a mandatory parameter, which specifies the position from where the replacement needs to be started. This parameter holds the integer value. There are three conditions for this parameter:
$length (optional) - It is an optional parameter of this function, which specifies how many characters, are to be replaced in the string. In case $length parameter is not passed in substr_replace(), then replacement stops at the end of the string. There are also three conditions for this parameter:
Return ValuesThe substr_raplace() returns a string after the replacement is done. In case, if the string is an array, then it returns an array. ChangeLogFrom PHP 4.3.3, all the parameters accept arrays. ExamplesThere are a few numbers of examples given, by which we can learn the practical implementation of the substr_replace() function. Example 1 Output: In the above example, replacement is started from 6th position. "earth" is replaced with "javatpoint". Hello javatpoint Example 2 Output: In the above example, replacement is started from 6th position in the first case. In the second case, a negative value is passed, so replacement is done at the end from 10th position in the string. Hello PHP Hello PHP Example 3 Output: In the above example, we have used the fourth $length parameter, whose value is passed 0. Hence the insertion of string "Hello" is done rather than replacement. Hello PHP! Example 4 Output: Welcome to javatpoint Example 5: Replacement multiple strings at once Output: X: BBBB; Y: BBBB; Z: BBBB X: XXXX; Y: YYYY; Z: ZZZZ X: XXXXAA; Y: YYYYA; Z: ZZZZ Note: Implode() function is used here for the array to string conversion.Next TopicPHP String Functions |