How to implement string replacement in php: first create a PHP sample file; then replace the string through the "str_replace("red","black","red green yellow pink purple");" method; Finally, the replacement result can be output through echo.
The operating environment of this tutorial: Windows 7 system, PHP version 5.6. This method is suitable for all brands of computers.
Recommended: "PHP Video Tutorial"
PHP string replacement str_replace() function four usages
Parameters $search, the string or array to be replaced
Parameter $replace, the string or array to be replaced
Parameter $subject, the string or array to be queried
Parameter $count, optional, if specified, will be set to the number of replacements
Return value: This function returns the replaced array or string (newly generated)
Example 1: String replaces string
$str1 = str_replace("red","black","red green yellow pink purple"); echo $str1.""; //输出结果为black green yellow pink purple
Example 2: String replaces array key value
$arr = array("blue","red","green","yellow"); $str1 = str_replace("red","pink",$arr,$i); print_r($str1);
Example 3: Array replaces array, mapping replaces
$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);
Example 4 : If $search is an array and $replace is a string
$search = array("banana","grape"); $replace = "tomato"; $arr = array("banana","apple","orange","grape"); $new_arr = str_replace($search,$replace,$arr,$count); print_r($new_arr);
For more programming-related knowledge, please visit: Programming Learning Course! !
The above is the detailed content of How to replace strings in php. For more information, please follow other related articles on the PHP Chinese website!