PHP字符串函数substr_replace(替换字符串的子串)

   在PHP中,字符串函数 substr_replace() 用来替换字符串的子串。

    函数语法:

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

    函数参数说明:

参数描述
string必需。规定要检查的字符串。
replacement必需。规定要插入的字符串。
start必需。规定在字符串的何处开始替换。
  • 正数 - 在字符串的指定索引位置开始

  • 负数 - 在字符串的倒数指定位置开始

  • 0 - 在字符串中的第一个字符处开始

length可选。规定要替换多少个字符。默认是与字符串长度相同。
  • 正数 - 被替换的字符串长度

  • 负数 - 表示待替换的子字符串结尾处距离 string 末端的字符个数(即还剩余多少字符不需要替换)

  • 0 - 插入而非替换

    substr_replace() 函数用来将字符串 string 的副本中由 start 和可选的 length 参数限定的子字符串使用 replacement 进行替换,返回结果字符串。如果 string 是个数组,那么也将返回一个数组。

    举例1,替换子串   

<?php
// 替换字符串的子串
$rawStr = 'hello world';
// 从字符串的索引为6的字符开始替换
$res1 = substr_replace($rawStr, 'china', 6);
// 从字符串的尾部第5个字符开始替换
$res2 = substr_replace($rawStr, 'china', -5);

// 输出
echo $res1;
echo '<br>';
echo $res2;

    以上代码输出如下(指定正数和相应的负数结果相同):

hello china
hello china

     举例2,替换子串(指定start和length)   

<?php
// 替换字符串的子串
$rawStr = 'hello world';
// 从字符串的索引为6的字符开始替换,替换长度为0
$res1 = substr_replace($rawStr, 'china', 6, 0);

// 从字符串的尾部第5个字符开始替换,替换长度为0
$res2 = substr_replace($rawStr, 'china', -5, 0);
// 从字符串的尾部第5个字符开始替换,尾部剩余不替换字符个数为5
$res3 = substr_replace($rawStr, 'china', -5, -5);
// 从字符串的尾部第5个字符开始替换,尾部剩余不替换字符个数为4(world的w字符被替换,剩余orld)
$res4 = substr_replace($rawStr, 'china', -5, -4);

// 输出
echo $res1;
echo '<br>';
echo $res2;
echo '<br>';
echo $res3;
echo '<br>';
echo $res4;

    以上代码输出如下(请注意不同替换长度时的结果):

hello chinaworld
hello chinaworld
hello chinaworld
hello chinaorld

     举例3,数组子串替换(原理和字符串一样)   

<?php
// 替换数组的子串
$rawArr = ['hello', 'world'];
// 数组的每个子串单独进行替换(原理和字符串一样)
$res1 = substr_replace($rawArr, ['hi', 'china'], 0);
var_dump($res1);

// 数组的每个子串单独进行替换(原理和字符串一样,替换2个字符)
$res2 = substr_replace($rawArr, ['hi', 'china'], 0, 2);
var_dump($res2);

    以上代码输出如下:

array (size=2)
  0 => string 'hi' (length=2)
  1 => string 'china' (length=5)
E:\apps\wamp\www\demo\test\index.php:10:array (size=2)
  0 => string 'hillo' (length=5)
  1 => string 'chinarld' (length=8)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值