Replace "Hello" with "world":
<?phpecho substr_replace("Hello","world",0);?>The substr_replace() function replaces part of a string with another string.
Note: If the start parameter is negative and length is less than or equal to start, length is 0.
Note: This function is binary safe.
substr_replace( string,replacement,start,length )
parameter | describe |
---|---|
string | Required. Specifies the string to check. |
replacement | Required. Specifies the string to be inserted. |
start | Required. Specifies where in the string to begin replacement. Positive number - starts at the specified position in the string Negative numbers - start at the specified position from the end of the string 0 - Start at the first character in the string |
length | Optional. Specifies how many characters to replace. The default is the same as the string length. Positive number - the length of the string to be replaced Negative number - the number of characters to be replaced starting from the end of the string 0 - insert instead of replace |
Return value: | Returns the replaced string. If string is an array, the array is returned. |
---|---|
PHP version: | 4+ |
Update log: | As of PHP 4.3.3, all parameters accept arrays. |
Replace starting from the 6th position of the string (replace "world" with "earth"):
<?phpecho substr_replace("Hello world","earth",6);?>Replace starting from the 5th position at the end of the string (replace "world" with "earth"):
<?phpecho substr_replace("Hello world","earth",-5);?>Insert "Hello" at the beginning of "world":
<?phpecho substr_replace("world","Hello ",0,0);?>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)) ;?>