substr_replace()
function replaces part of the string with another string.
Note: If the start parameter is a negative number and length is less than or equal to start , then length is 0.
Note: This function is binary safe.
Replace "Hello" with "world":
<?php echo substr_replace ( "Hello" , "world" , 0 ) ; ?>
Try it yourself
Replace from the 6th position of the string (replace "world" with "Shanghai"):
<?php echo substr_replace ( "Hello world" , "Shanghai" , 6 ) ; ?>
Try it yourself
Replace from the 5th position at the end of the string (replace "world" with "Shanghai"):
<?php echo substr_replace ( "Hello world" , "Shanghai" , - 5 ) ; ?>
Try it yourself
Insert "Hello" at the beginning of "world":
<?php echo substr_replace ( "world" , "Hello " , 0 , 0 ) ; ?>
Try it yourself
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 ) ) ; ?>
Try it yourself
substr_replace ( string , replacement , start , length )
parameter | describe |
---|---|
string | Required. Specifies the string to be checked. |
replacement | Required. Specifies the string to be inserted. |
start |
Required. Specifies where to start the replacement of the string.
|
length |
Optional. Specify how many characters to replace. The default is the same length as the string.
|