Home > Article > Backend Development > How to replace specified characters in a string in php
The way to replace specified characters in a string in php is: you can use the str_replace() function. This function can replace some characters in a string and return a string or array with the replacement values. Syntax: [str_replace(find,replace,string,count)].
#If you want to replace specified characters in a string, then we can use the str_replace() function to achieve this.
(Recommended tutorial: php tutorial)
Function introduction:
str_replace() function replaces some characters in the string (case sensitive) . This function returns a string or array with replacement values.
When using this function, you need to pay attention to the following rules:
If the searched string is an array, then it will return an array.
If the searched string is an array, then it will find and replace each element in the array.
If an array needs to be searched and replaced at the same time, and the elements to be replaced are less than the number of found elements, the excess elements will be replaced with empty strings .
If you search an array and replace only one string, the replacement string will work for all found values.
Syntax:
str_replace(find,replace,string,count)
Parameter description:
<?php //实例一:字符串替换字符串 $str1 = str_replace("red","black","red green yellow pink purple"); echo $str1.""; //输出结果为black green yellow pink purple ?> <?php //实例二:字符串替换数组键值 $arr = array("blue","red","green","yellow"); $str1 = str_replace("red","pink",$arr,$i); print_r($str1); ?> <?php //实例三:数组替换数组,映射替换 $arr1 = array("banana","orange"); $arr2 = array("pitaya","tomato"); $con_arr = array("apple","orange","banana","grape"); $con_rep = str_replace($arr1,$arr2,$con_arr,$count); print_r($con_rep); ?> <?php //实例四:如$search为数组,$replace为字符串时 $search = array("banana","grape"); $replace = "tomato"; $arr = array("banana","apple","orange","grape"); $new_arr = str_replace($search,$replace,$arr,$count); print_r($new_arr); ?
The above is the detailed content of How to replace specified characters in a string in php. For more information, please follow other related articles on the PHP Chinese website!