PHP substr_replace() function

Example

Replace "Hello" with "world":

<?php
echo substr_replace("Hello","world",0);
?>

Run Examples

Definition and Usage

The substr_replace() function replaces a part of the string with another string.

Note:If start The parameter is negative and length less than or equal to start, then length is 0.

Note:This function is binary safe.

Syntax

substr_replace(string,replacement,start,length)
Parameters Description
string Required. Specifies the string to be checked.
replacement Required. Specifies the string to be inserted.
start

Required. Specifies where to start replacing in the string.

  • Positive number - starts replacing from the specified position in the string
  • Negative number - starts replacing from the specified position from the end of the string
  • 0 - Start replacing at the first character in the string
length

Optional. Specifies how many characters to replace. The default is the same as the length of the string.

  • Positive number - the length of the replaced string
  • Negative number - indicates the distance from the end of the substring to be replaced string Number of characters at the end.
  • 0 - Insertion instead of replacement

Technical Details

Return Value: Returns the replaced string. If string If it is an array, it returns an array.
PHP Version: 4+
Update Log: Starting from PHP 4.3.3, all parameters accept arrays.

More Examples

Example 1

Replace starting from the 6th character of the string (replace "world" with "Shanghai"):

<?php
echo substr_replace("Hello world","Shanghai",6);
?>

Run Examples

Example 2

Replace starting from the 5th character from the end of the string (replace "world" with "Shanghai"):

<?php
echo substr_replace("Hello world","Shanghai",-5);
?>

Run Examples

Example 3

Insert "Hello" at the beginning of "world":

<?php
echo substr_replace("world","Hello ",0,0);
?>

Run Examples

Example 4

Replace multiple strings at once. Replace "AAA" with "BBB" in each string:

<?php
$replace = array("1: AAA","2: AAA","3: AAA");
echo implode("<br>",substr_replace($replace,'BBB',3,3));
?>

Run Examples