The substr_replace() function replaces one string with another string.
PHP substr_replace() Function has the following syntax.
substr_replace(string,replacement,start,length)
Parameter | Is Required | Description |
---|---|---|
string | Required. | String to check |
replacement | Required. | String to insert |
start | Required. | Where to start replacing in the string
|
length | Optional. | Specifies how many characters should be replaced.
|
PHP substr_replace() Function returns the replaced string. If the string is an array then the array is returned.
Replace "Hello" with "world":
<?php
echo substr_replace("Hello world from java2s.com","world",0);
?>
The code above generates the following result.
Start replacing at the 6th position in the string (replace "world" with "earth"):
<?php
echo substr_replace("Hello world","earth",6);
?>
The code above generates the following result.
Start replacing at the 5th position from the end of the string (replace "world" with "earth"):
<?php
echo substr_replace("Hello world","earth",-5);
?>
The code above generates the following result.
Insert "Hello" at the beginning of "world":
<?php
echo substr_replace("world","Hello ",0,0);
?>
The code above generates the following result.
Replace multiple strings at once. Replace "AAA" in each string with "BBB":
<?php
$replace = array("1: AAA","2: AAA","3: AAA");
echo implode("<br>",substr_replace($replace,'BBB',3,3));
?>
The code above generates the following result.