Home > Article > Backend Development > How to use replace string function in php
How to use the replace string function in php: 1. [$search] The string or array to be replaced; 2. [$replace] The string or array to be replaced; 3. [$ subject] The string or array being queried; 4. [$count] is optional. If specified, it will be set to the number of replacements.

php method of using the replace string function:
PHP string replacementstr_replace()Four ways to use the function, the specific content is as follows:
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
This function returns a string or array. This string or array is the result of replacing all searches in the subject with replace.
1, $search, the string to be replaced, or array
2, $replace, the string to be replaced or Array
3, $subject, the queried string or array
4, $count, optional, if specified, will Set to the number of times of replacement
5. Return value: This function returns the replaced array or string (newly generated)
<?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);
?>Related learning recommendations:php Programming(Video)
The above is the detailed content of How to use replace string function in php. For more information, please follow other related articles on the PHP Chinese website!