PHP substr_replace() Function
Definition
The substr_replace() function replaces one string with another string.
Syntax
PHP substr_replace() Function has the following syntax.
substr_replace(string,replacement,start,length)
Parameter
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.
|
Return
PHP substr_replace() Function returns the replaced string. If the string is an array then the array is returned.
Example 1
Replace "Hello" with "world":
<?php
echo substr_replace("Hello world from java2s.com","world",0);
?>
The code above generates the following result.
Example 2
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.
Example 3
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.
Example 4
Insert "Hello" at the beginning of "world":
<?php
echo substr_replace("world","Hello ",0,0);
?>
The code above generates the following result.
Example 5
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.