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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

substr_replace(array|string $string, array|string $replace, array|int $offset, array|int|null $length = null): string|array

Parameters

ParameterDescription
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

Mask a card numberTry it yourself
<?php
$card = "4111222233334444";
echo substr_replace($card, str_repeat("*", 12), 0, 12), "\n";

Output

************4444
Insert and replace the endTry it yourself
<?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

VersionChange
PHP 4.0Added

Was this page helpful?