PHP 里替换字符串有两条路:按内容查找替换,用 str_replace() / str_ireplace();按位置替换,用 substr_replace()。这篇把两者的语法和差异放在一起记一下。
![图片[1]-PHP字符串替换-本站](https://blog.azhai.de/wp-content/uploads/9791230b3881-500x281.jpg)
str_replace() 与 str_ireplace()
用新字符串替换掉字符串中指定的内容。唯一区别:str_replace() 区分大小写,str_ireplace() 不区分,语法一致:
str_replace(find,replace,string,count)
str_ireplace(find,replace,string,count)
//find必需。规定要查找的值。
//replace必需。规定替换 find 中的值的值。
//string必需。规定被搜索的字符串。
//count可选。对替换数进行计数的变量。
substr_replace()
把字符串从指定位置开始的一部分替换成另一个字符串,start 是起始位置,length 是被替换的长度:
substr_replace(string,replacement,start,length)
![图片[2]-PHP字符串替换-本站](https://i1.img.azhai.de/v2/c2ee673548b7cfdd.png)
示例
<?php
$str = 'hello,world,hello,world';
$replace = 'hi';
echo substr_replace($str, $replace, 0,5);
?>
//输出结果hi,world,hello,world
输出 hi,world,hello,world,即从位置 0 开始把前 5 个字符换成 hi。
使用注意
count参数是引用传递,用来记录实际替换了多少次。substr_replace()的start为负数时从字符串末尾倒数定位。- 对数组传入
str_replace()会逐个元素替换并返回数组。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END

















暂无评论内容