这篇文章主要讲解了“php如何进行字符串替换”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“php如何进行字符串替换”吧!
字符串替换方法:1、使用str_replace()函数,语法“str_replace(查找值,替换值,字符串)”;2、使用substr_replace()函数,语法“substr_replace(字符串,替换值,开始位置,替换长度)”。

本教程操作环境:windows7系统、PHP7.1版、DELL G3电脑
在 PHP 中,可以对一个字符串中的特定字符或子串进行替换,这是非常常用的功能。
php进行字符串替换
方法1:str_ireplace() 和 str_replace() 函数
str_ireplace() 和 str_replace 使用新的字符串替换原来字符串中指定的特定字符串,str_replace 区分大小写,str_ireplace() 不区分大小写,两者语法相似。
str_replace(find,replace,string,count)
str_ireplace(find,replace,string,count)
| 参数 | 描述 |
|---|
| find | 必需。规定要查找的值。 |
| replace | 必需。规定替换 find 中的值的值。 |
| string | 必需。规定被搜索的字符串。 |
| count | 可选。对替换数进行计数的变量。 |
示例:
<?php
header("Content-type:text/html;charset=utf-8");
$str = 'hello,world,Hello,world';
echo "原字符串:".$str."<br>";
$search = 'hello';
$replace = 'hi';
echo "<br>替换字符串:<br>";
echo str_replace($search, $replace, $str)."<br>";
echo str_ireplace($search, $replace, $str)."<br>";
?>
方法2:substr_replace() 函数
substr_replace() 函数把字符串的一部分替换为另一个字符串。
substr_replace() 函数的语法如下:
substr_replace(string,replacement,start,length)
| 参数 | 描述 |
|---|
| string | 必需。规定要检查的字符串。 |
| replacement | 必需。规定要插入的字符串。 |
| start | 必需。规定在字符串的何处开始替换。正数 - 在字符串的指定位置开始 负数 - 在从字符串结尾的指定位置开始 0 - 在字符串中的第一个字符处开始
|
| length | 可选。规定要替换多少个字符。默认是与字符串长度相同。正数 - 被替换的字符串长度 负数 - 从字符串末端开始的被替换字符数 0 - 插入而非替换
|
示例:
<?php
$str = 'hello,world,hello,world';
$replace = 'hi';
echo substr_replace($str, $replace, 0,5);
?>
以上代码的执行结果为:
hi,world,hello,world
感谢各位的阅读,以上就是“php如何进行字符串替换”的内容了,经过本文的学习后,相信大家对php如何进行字符串替换这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是天达云,小编将为大家推送更多相关知识点的文章,欢迎关注!