Detailed explanation of 4 usages of PHP string replacement str_replace() function

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
This function returns a string or an array. The string or array is the result of replacing all searches in subject with replace.
1, $search, the string or array to be replaced
2, $replace, the string or array to be replaced
3, $subject, the string or array to be queried
4, $count, optional, if specified , it will be set to the number of times of replacement
5. Return value: This function returns the replaced array or string (newly generated)

<?php
	//Example 1: String replacement string
	$str1 = str_replace("red","black","red green yellow pink purple");
	echo $str1.""; //The output result is black green yellow pink purple
?>

 

<?php
	//Example 2: String replacement array key value
	$arr = array("blue","red","green","yellow");
	$str1 = str_replace("red","pink",$arr,$i);
	print_r($str1);
?>

 

<?php
	//Example 3: Array replaces array, map 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);
?>

 

<?php
	//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);
?>

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326683273&siteId=291194637