Home >Backend Development >PHP Problem >How to replace matching string in php

How to replace matching string in php

藏色散人
藏色散人Original
2020-09-01 10:05:593306browse

php method to replace the matching string: 1. Use the "str_replace" function to replace the matching string; 2. Use the "substr_replace" function to replace the matching string.

How to replace matching string in php

Recommendation: "PHP Video Tutorial"

Find and replace php strings

Two major functions for string search and replacement

* 1.str_replace()
* 2.substr_replace()
 
 
$str = 'Peter Zhu is PHP lecture';
//二、str_replace()
//1.str_replace()
echo str_replace(&#39;php&#39;,&#39;JAVA&#39;,$str).&#39;<br>&#39;;
//2.删除指定字符:用空字符替换即可
echo str_replace(&#39;Zhu&#39;,&#39;&#39;,$str).&#39;<br>&#39;;
//3.要被替换的多个子字符串,可以存放到数组中
echo str_replace([&#39;Zhu&#39;,&#39;PHP&#39;],&#39;王楚&#39;,$str).&#39;<br>&#39;;
//4.新字符串也可以来自数组,但数量必须要被替换数组相同
echo str_replace([&#39;Zhu&#39;,&#39;PHP&#39;],[&#39;Wang&#39;,&#39;python&#39;],$str).&#39;<br>&#39;;
 
//类似:str_ireplace()你可能已经猜到了,这是不区分被替换字符串大小写的替换
echo str_ireplace(&#39;php&#39;,&#39;python&#39;,$str).&#39;<hr>&#39;;
 
 
 
//二、substr_replace($str, $object, $offset, $length),$offset和$length指定了替换的索引区间
//从0开始替换到$str结束,用新字符串:PHP是最好的编程语言
echo substr_replace($str,&#39;php是世界上最好的编程语言&#39;,0).&#39;<br>&#39;;
//等价于
echo substr_replace($str,&#39;php是世界上最好的编程语言&#39;,0,strlen($str)).&#39;<br>&#39;;
 
//在$str中插入字符
//插入后的结果如下: Peter Zhu is PHP中文网的PHP leture
//其中: PHP中文网 是插入的内容, $length=0,表示插入到这个位置
//第四个参数,就是要替换的长度
echo substr_replace($str,&#39;php中文网&#39;,13,0).&#39;<br>&#39;;
 
//将PHP替换成JAVA
echo substr_replace($str,&#39;java&#39;,13,3 ).&#39;<br>&#39;;
 
//删除指定区间内的字符,将新字符设置为空字符即可
//删除&#39;Zhu&#39;
echo substr_replace($str,&#39;&#39;,6,3),&#39;<br>&#39;;

The above is the detailed content of How to replace matching string in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn