PHP 8 reference · String Functions
PHP substr_replace() Function
Replace part of a string, given a start position and length, with another string. Also inserts text or masks digits.
PHP 8 Since 4.0
Syntax
substr_replace(array|string $string, array|string $replace, array|int $offset, array|int|null $length = null): string|array
Parameters
| Parameter | Description |
|---|---|
string |
The input string. |
replace |
The text to put in. |
offset |
Where to start; negative counts from the end. |
length optional |
How many bytes to replace. 0 inserts without removing; null replaces to the end. |
Return value
The new string.
Examples
<?php
$card = "4111222233334444";
echo substr_replace($card, str_repeat("*", 12), 0, 12), "\n";
Output
************4444
<?php
echo substr_replace("Hello World", "Big ", 6, 0), "\n"; // insert
echo substr_replace("report.txt", "pdf", -3), "\n"; // replace the end
Output
Hello Big World report.pdf
Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
Related
str_replace()· Replace every occurrence of a search string with a replacement. Accepts arrays to make several replacements at once.substr()· Return part of a string, given a start position and an optional length. Negative values count from the end.- PHP Strings · tutorial