Instance
Replace "Hello" with "World":
<?phpecho substr_replace ("Hello", "World", 0);? >
Definition and usage
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.
Grammar
Substr_replace (String,replacement,start,length)
Parameters |
Describe |
String |
Necessary. Specifies the string to check. |
Replacement |
Necessary. Specifies the string to insert. |
Start |
Necessary. Specifies where the string begins to be replaced.
Positive number-starts at the specified position in the string
Negative number-starts at the specified position from the end of the string
0-Starts at the first character in a string
|
Length |
Optional. Specifies the number of characters to replace. The default is the same length as the string.
Positive number-The length of the string being replaced
Negative-the number of characters to be replaced starting at the end of the string
0-Insert rather than replace
|
Technical details
return value: |
returns the replaced string. If the string is an array, the array is returned. |
php version: |
4+ |
update log: |
since PHP 4.3.3, all parameters accept arrays. |
More examples
Example 1
Replace from the 6th position of the string (replace "World" with "Earth"):
<?phpecho substr_replace ("Hello World", "Earth", 6);? >
Example 2
Start with the 5th position at the end of the string (replace "World" with "Earth"):
<?phpecho substr_replace ("Hello World", "Earth",-5);? >
Example 3
Insert "Hello" at the beginning of "World":
<?phpecho Substr_replace ("World", "Hello", 0,0);? >
Example 4
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));? >
Example:
<?phpecho substr_replace (' abcdef ', ' # # # ', 1);//Output a## #echo substr_replace (' ABCdef ', ' # # # ', 1, 2);//Output a## #defecho substr_replace (' abcdef ', ' # # ',-3, 2);//Output abc## #fecho substr_replace (' abcdef ', ' # # # ', 1,-2);//output a## #ef;