Home > Article > Backend Development > How to replace multiple characters at the same time with php str_replace
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.
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('a','-',$str); echo $newStr."<br>"; ?>
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(['a','b','c'],'-',$str);//a或b或c都替换成- echo $newStr."<br>"; ?>
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(['a','b','c'],['-','!','~'],$str);//a->- b->! c->~ echo $newStr."<br>"; ?>
#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!