PHP substr_replace () function
Examples
The "Hello" replace "world":
<?php
echo substr_replace("Hello","world",0);
?>
echo substr_replace("Hello","world",0);
?>
Running instance »
Definition and Usage
substr_replace () function replaces part of a string with another string.
Note: If thestart argument is negative and the length is less than or equal to start, then the length is zero.
Note: This function is binary safe.
grammar
substr_replace( string,replacement,start,length )
参数 | 描述 |
---|---|
string | 必需。规定要检查的字符串。 |
replacement | 必需。规定要插入的字符串。 |
start | 必需。规定在字符串的何处开始替换。
|
length | 可选。规定要替换多少个字符。默认是与字符串长度相同。
|
technical details
return value: | Returns the string to be replaced. If the string is an array, the array is returned. |
---|---|
PHP version: | 4+ |
Update log: | Since PHP 4.3.3 onwards, all parameters are accepted arrays. |
More examples
Example 1
Replace start from the 6th position in the string (the "world" replaced by "earth"):
<?php
echo substr_replace("Hello world","earth",6);
?>
echo substr_replace("Hello world","earth",6);
?>
Running instance »
Example 2
Replace start from the 5th position end of the string (the "world" replaced by "earth"):
<?php
echo substr_replace("Hello world","earth",-5);
?>
echo substr_replace("Hello world","earth",-5);
?>
Running instance »
Example 3
At the beginning of "world" insert "Hello":
<?php
echo substr_replace("world","Hello ",0,0);
?>
echo substr_replace("world","Hello ",0,0);
?>
Running instance »
Example 4
Replace multiple strings at once. Each string "AAA" replace "BBB":
<?php
$replace = array("1: AAA","2: AAA","3: AAA");
echo implode("<br>",substr_replace($replace,'BBB',3,3));
?>
$replace = array("1: AAA","2: AAA","3: AAA");
echo implode("<br>",substr_replace($replace,'BBB',3,3));
?>
Running instance »
PHP String Reference