字符串替换方法:1、使用str_replace()函数,语法“str_replace(查找值,替换值,字符串)”;2、使用substr_replace()函数,语法“substr_replace(字符串,替换值,开始位置,替换长度)”。

本教程操作环境:windows7系统、PHP7.1版、DELL G3电脑
在 PHP 中,可以对一个字符串中的特定字符或子串进行替换,这是非常常用的功能。
php进行字符串替换
方法1:str_ireplace() 和 str_replace() 函数
立即学习“PHP免费学习笔记(深入)”;
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 | 必需。规定在字符串的何处开始替换。
|
| length | 可选。规定要替换多少个字符。默认是与字符串长度相同。
|
示例:
<?php $str = 'hello,world,hello,world'; $replace = 'hi'; echo substr_replace($str, $replace, 0,5); ?>
以上代码的执行结果为:
hi,world,hello,world
推荐学习:《PHP视频教程》
以上就是php怎么进行字符串替换的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号