83 of 410 menu

The substr_replace Function

The substr_replace function replaces a specified part of a string with another. This function cuts out a specified part of a string (parameters specify where to start cutting and how many characters to take) and replaces the cut-out part with the specified string. If the last parameter is not specified, the replacement will be performed until the end of the string.

Syntax

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

Example

Let's cut out characters from the string, starting from the first one (character numbering starts from zero), 3 pieces, and insert '!!!' instead:

<?php echo substr_replace('abcde', '!!!', 1, 3); ?>

Code execution result:

'a!!!e'

Example

Let's cut out characters from the string, starting from the first one to the end of the string (since the last parameter is not specified) and insert '!!!' instead:

<?php echo substr_replace('abcde', '!!!', 1); ?>

Code execution result:

'a!!!'

See Also

  • the str_replace function,
    which performs search and replace within a string
  • the substr function,
    which extracts a part of a substring
byenru