Latest web development tutorials

PHP substr_replace () function

PHP String Reference PHP String Reference

Examples

The "Hello" replace "world":

<?php
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 必需。规定在字符串的何处开始替换。
  • 正数 - 在字符串的指定位置开始
  • 负数 - 在从字符串结尾的指定位置开始
  • 0 - 在字符串中的第一个字符处开始
length 可选。规定要替换多少个字符。默认是与字符串长度相同。
  • 正数 - 被替换的字符串长度
  • 负数 - 从字符串末端开始的被替换字符数
  • 0 - 插入而非替换

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);
?>

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);
?>

Running instance »

Example 3

At the beginning of "world" insert "Hello":

<?php
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));
?>

Running instance »


PHP String Reference PHP String Reference