substr_replace()
substr_replace() — Replace text within a portion of a string.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
substr_replace() replaces a copy of string delimited by the offset and (optionally) length parameters with the string given in replace.
Signature
substr_replace(array|string $string, array|string $replace, array|int $offset, array|int|null $length = null): string|array
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $string | array|string | The input string. |
| $replace | array|string | The replacement string. |
| $offset | array|int | If offset is non-negative, the replacing will begin at the offset'th offset into string. |
| $length | array|int|null | If given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing. If it is not given, then it will default to strlen( string ); i.e. end the replacing at the end of string. Of course, if length is zero then this function will have the effect of inserting replace into string ... |
Return value
The result string is returned. If string is an array then array is returned.
Example
A runnable snippet:
$var = 'ABCDEFGH:/MNRPQR/'; echo "Original: $var<hr />\n"; /* These two examples replace all of $var with 'bob'. */ echo substr_replace($var, 'bob', 0) . "<br />\n"; echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n"; /* Insert 'bob' right at the beginning of $var. */ echo substr_replace($var, 'bob', 0, 0) . "<br />\n"; /* These next two replace 'MNRPQR' in $var with 'bob'. */ echo substr_replace($var, 'bob', 10, -1) . "<br />\n"; echo substr_replace($var, 'bob', -7, -1) . "<br />\n"; /* Delete 'MNRPQR' from $var. */ echo substr_replace($var, '', 10, -1) . "<br />\n";
Changelog
| Version | Change |
|---|---|
| 8.0.0 | length is nullable now. |
See also
All PHP 8.5 built-in functions
Reference card built from the PHP manual page substr_replace() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.