substr_replace
Replaces part of a string by position.
Syntax
substr_replace(string $string, string $replace, int $offset, ?int $length = null): stringParameters
| Parameter | Type | Description |
|---|---|---|
| $string | string | The input string. |
| $replace | string | The replacement. |
| $offset | int | Where to start; negative counts from the end. |
| $length | ?int | Optional. How many characters to replace. |
Return value
stringThe string with the part replaced.
Examples
Masking the middle of a card number:
<?php
echo substr_replace('4276123456789012', '********', 4, 8);Output:
4276********9012Inserting without replacing — length 0:
<?php
echo substr_replace('2026-1002', '-', 7, 0);Output:
2026-10-02Notes
The function counts bytes. For multibyte text build the result from mb_substr() pieces.
See also
- substr — Returns part of a string, counting in bytes.
- str_replace — Replaces all occurrences of a substring with another string.
- str_pad — Pads a string to a given length.
Related recipes
In the tutorial
- Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.