首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[函数]substr_replace()函数—用法及示例

发布于 2025-05-08 19:35:41
0
11

函数名:substr_replace()

函数描述:substr_replace() 函数用于将字符串的一部分替换为另一个字符串。

参数:

  • string:必需。原始字符串。
  • replacement:必需。替换字符串。
  • start:必需。替换的起始位置。如果 start 是正数,则从字符串的 start 位置开始替换。如果是负数,则从字符串末尾的 start 位置开始替换。
  • length:可选。替换的长度。如果省略,则替换从 start 位置开始到字符串末尾的所有字符。
  • encoding:可选。指定字符编码。常用的编码有 "UTF-8"、"ISO-8859-1" 等。

返回值:返回替换后的字符串。

示例:

$str = "Hello, world!";
$replacement = "PHP";
$start = 7;

// 替换字符串的一部分为 "PHP"
$result = substr_replace($str, $replacement, $start);
echo $result; // 输出 "Hello, PHP!"

$str2 = "Hello, world!";
$replacement2 = "PHP";
$start2 = -6;
$length2 = 5;

// 替换字符串的一部分为 "PHP",从倒数第6个字符开始,替换长度为5
$result2 = substr_replace($str2, $replacement2, $start2, $length2);
echo $result2; // 输出 "Hello, PHP!"

$str3 = "Hello, world!";
$replacement3 = "PHP";
$start3 = 7;
$length3 = 5;

// 替换字符串的一部分为 "PHP",从第7个字符开始,替换长度为5
$result3 = substr_replace($str3, $replacement3, $start3, $length3);
echo $result3; // 输出 "Hello, PHP, world!"

注意:substr_replace() 函数在 PHP 5 及以上版本可用。

评论
啊龙
Lv.1普通用户

8568

帖子

29

小组

2696

积分

站长交流