Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP substr_replace() function

Reference for PHP substr_replace(): replace, insert or remove part of a string by position and length, negative values and processing arrays of strings.

substr_replace() replaces a section of a string, chosen by position and length rather than by content. Depending on the arguments it can overwrite part of a string, insert text at a position (length 0), or delete a section (empty replacement).

Use str_replace() when you know what to replace, and substr_replace() when you know where.

PHP
<?php
echo substr_replace("Hello world", "PHP", 6, 5);   // Hello PHP
echo substr_replace("Hello", "!!", 5, 0);          // Hello!!

Try it

PHP Replace, insert and remove

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Masking and arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
substr_replace(
    array|string $string,
    array|string $replace,
    array|int $offset,
    array|int|null $length = null
): string|array
Name Description
$string The input string, or an array of strings.
$replace The replacement text (or an array, one per element when $string is an array).
$offset Where replacement starts. Negative counts from the end. If larger than the length, the text is appended.
$length How many bytes to replace. 0 inserts. Negative stops that many bytes before the end. null or omitted: to the end of the string.

Return value: the resulting string, or an array of strings when $string is an array.

Usage notes

  • Insert with length 0; delete with an empty $replace.
  • Length omitted means "to the end", not "the same length as the replacement".
  • Arrays. When $string is an array, $offset and $length may also be arrays; scalar values apply to every element. Missing array entries use the defaults.
  • Bytes. Positions are byte-based; there is no mb_substr_replace(), so for UTF-8 text build the result with mb_substr() pieces.
  • Original unchanged. PHP strings are values; the function returns a new string.
  • Common mistake: calling substr_replace($s, "x", 3) expecting to insert; it replaces everything from index 3 onward.
  • PHP 8.0: $length accepts null explicitly.