php怎么进行字符串替换
- 建站笔记
- 2022-05-17
- 598
字符串替换方法: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)
示例:
<?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)
示例:
<?php $str = 'hello,world,hello,world'; $replace = 'hi'; echo substr_replace($str, $replace, 0,5); ?>
以上代码的执行结果为:
hi,world,hello,world
本文由白琉璃于2022-05-17发表在白琉璃源码网,如有侵权或疑问,请联系我们,谢谢。
本文链接:https://www.bailiuli.com/t/2345.html
发表评论