substr_replace()

1. 定义

该函数替换指定位置开始后的子字符串,返回替换后的字符串。

注:与函数str_replace()不同的是,str_replace()带有“搜索”、“匹配”的性质,可指定替换次数;而substr_replace()需要知道替换开始的位置,并且只能发生一次替换。

2. 语法

substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] ) : mixed

3. 参数说明

参数 可选性 数据类型 描述
$string 必需 字符串或数组 将被替换的字符串或数组
$replacement 必需 字符串 替换值
$start 必需 字符串或数组 替换开始的位置索引
$length 可选 整型 被替换的子串长度,如果没有指定,则默认为字符串的长度(即从$start开始进行全部替换)

4. 示例

<?php

// substr_replace()
// 替换指定位置开始后的子字符串,返回替换后的字符串

$str = 'Hello, World!';
$replacement = '(__replaced__)';
$start = 2;
$res = substr_replace($str, $replacement, $start);
var_dump($res);// 输出:string(16) "He(__replaced__)"

// 从索引值为2(即第三位字符)开始,被替换的子字符串长度
$length = 4;
$res = substr_replace($str, $replacement, $start, $length);
var_dump($res);// 输出:string(23) "He(__replaced__) World!"

// 当被替换的字符串和替换值都为数组时,将发生映射替换
$str = ['one', 'two', 'three'];
$replacement = ['=1', '=2', '=3'];
$start = 3;
$res = substr_replace($str, $replacement, $start);
var_dump($res);
/* 输出:
array(3) {
  [0]=>
  string(5) "one=1"
  [1]=>
  string(5) "two=2"
  [2]=>
  string(5) "thr=3"
}
*/

5. 延展阅读

  • str_replace():将指定字符串中特定的部分,替换成另一个字符串
  • substr():返回从某位置开始、特定长度的子字符串