Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

substr_replace

Replaces part of a string by position.

Syntax

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

Parameters

ParameterTypeDescription
$stringstringThe input string.
$replacestringThe replacement.
$offsetintWhere to start; negative counts from the end.
$length?intOptional. 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********9012

Inserting without replacing — length 0:

<?php
 
echo substr_replace('2026-1002', '-', 7, 0);

Output:

2026-10-02

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.