字符串替换方法: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>; ?>
substr_replace() 函数把字符串的一部分替换为另一个字符串。
substr_replace() 函数的语法如下:
substr_replace(string,replacement,start,length)
参数 | 描述 |
---|---|
string | 必需。规定要检查的字符串。 |
replacement | 必需。规定要插入的字符串。 |
start | 必需。规定在字符串的何处开始替换。
|
length | 可选。规定要替换多少个字符。默认是与字符串长度相同。
|
示例:
<?PHP $str = 'hello,world,hello,world'; $replace = 'hi'; echo substr_replace($str, $replace, 0,5); ?>
以上代码的执行结果为:
hi,world,hello,world
推荐学习:《PHP教程》
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。