PHP Function Reference

PHP substr_replace() Function



The PHP substr_replace() function is used to replace a part of a string with another string. This function replaces a copy of the string delimited by the offset and (optionally) length parameters with the replace string in replace.

Note: This function is binary-safe.

Syntax

substr_replace(string, replace, offset, length)

Parameters

string Required. Specify the input string. An array of strings can be provided, in which case the replacements will occur on each string in turn. In this case, the replace, offset and length parameters may be provided either as scalar values to be applied to each input string in turn, or as arrays, in which case the corresponding array element will be used for each input string.
replace Required. Specify the replacement string.
offset Required. Specify offset parameter which indicates the starting position in the string.
  • If it is non-negative, then the replacing will begin at that offset position in the string, counting from zero.
  • If it is negative, then the replacing will begin at the offset position from the end of string.
length Optional. Specify the length of the segment from string to replace. Default is to the end of the string.
  • If length is a non-negative number, then string will be replaced for length characters after the starting position.
  • If length is a negative number, then string will be replaced from the starting position up to length characters from the end of string.

Return Value

Returns the result string. If string is an array then array is returned.

Example: substr_replace() examples

The example below shows the usage of substr_replace() function.

<?php
//program to illustrate the substr_replace() function
echo "1. ".substr_replace("Hello World", "John", 6)."\n"; 
echo "2. ".substr_replace("Hello World", "John", -5)."\n";

echo "3. ".substr_replace("Hello ", "World", 6, 0)."\n"; 
echo "4. ".substr_replace("World", "Hello ", 0, 0)."\n";
?>

The output of the above code will be:

1. Hello John
2. Hello John
3. Hello World
4. Hello World

Example: using with an array

Consider one more example where this function is used with an array to replace the specified substring.

<?php
$Arr = array("Hello John", "Hello Kim", "Hello Marry");

$replace = array("Hi", "Hola", "Hallo");

//replacing with a scalar
print_r(substr_replace($Arr, "Hi", 0, 5));

echo "\n";

//replacing with an array
print_r(substr_replace($Arr, $replace, 0, 5));
?>

The output of the above code will be:

Array
(
    [0] => Hi John
    [1] => Hi Kim
    [2] => Hi Marry
)

Array
(
    [0] => Hi John
    [1] => Hola Kim
    [2] => Hallo Marry
)

❮ PHP String Reference