Home  >  Article  >  Backend Development  >  How to replace multiple characters at the same time with php str_replace

How to replace multiple characters at the same time with php str_replace

青灯夜游
青灯夜游Original
2022-04-25 19:52:564763browse

Method: Set the first parameter of str_replace() to an array, the syntax "str_replace(array,'replacement value',$str)" can replace multiple characters with the same specified character; If you want to replace it with a different specified character, you only need to set the second parameter to an array, and the number of elements in the two arrays must be the same.

How to replace multiple characters at the same time with php str_replace

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php str_replace simultaneously replace Multiple characters

str_replace() Replaces a specific string specified in the original string with a new string.

str_replace(find,replace,string,count)
Parameters Description
find Required . Specifies the value to look for.
replace Required. Specifies a value that replaces the value in find.
string Required. Specifies the string to be searched for.
count Optional. A variable counting the number of substitutions.

Generally, the str_replace() function only searches for one value and replaces it with the specified value.

<?php
$str = "abchelloabc";
$newStr=str_replace(&#39;a&#39;,&#39;-&#39;,$str);
echo $newStr."<br>";
?>

How to replace multiple characters at the same time with php str_replace

When the first parameter find of the function is set to an array type, multiple values ​​can be searched:

<?php
$str = "abchelloabc";
$newStr=str_replace([&#39;a&#39;,&#39;b&#39;,&#39;c&#39;],&#39;-&#39;,$str);//a或b或c都替换成-
echo $newStr."<br>";
?>

How to replace multiple characters at the same time with php str_replace

This is to replace multiple characters with the same specified character. If the second parameter replace of the function is also set to an array type, it can be replaced with different specified characters

<?php
$str = "abchelloabc";
$newStr=str_replace([&#39;a&#39;,&#39;b&#39;,&#39;c&#39;],[&#39;-&#39;,&#39;!&#39;,&#39;~&#39;],$str);//a->- b->! c->~
echo $newStr."<br>";
?>

How to replace multiple characters at the same time with php str_replace

#Note: At this time, the number of elements in the two arrays must be the same.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to replace multiple characters at the same time with php str_replace. 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