PHP str_replace() Function


str_replace() function replace a substring inside a string. It is much faster than other string replacement functions such as preg_replace() which use regular expression.

<?PHP
	$str="This is a PHP Tutorial";
	$str2=str_replace("PHP","Javascript",$str);
	echo "$str2"; //This is a Javascript Tutorial
?>

str_replace() can count the total replacement number.
<?PHP
	$str="The best time is no time at that time";
	$cnt=0;
	$str2=str_replace("time","TIME",$str,$cnt);
	echo "$cnt, $str2"; //3, The best TIME is no TIME at that TIME
?>

str_replace() supports array replacement. It will loop through the array, and do the replacement for each element.
<?PHP
	$str="The best time is no time at that time";
	$arr=array("mon","tue","wed","thr","fri","sat","sun");
	$cnt=0;
	$arr2=str_replace("fri","FRI",$arr,$cnt);
	print_r($arr2);
	//Array ( [0] => mon [1] => tue [2] => wed [3] => thr [4] => FRI [5] => sat [6] => sun )
	$arr3=str_replace("t","T",$arr,$cnt);
	print_r($arr3);
	//Array ( [0] => mon [1] => Tue [2] => wed [3] => Thr [4] => fri [5] => saT [6] => sun )
	echo "Total replacements: " . $cnt;  //1
?>

When the replacement is also an array, the 1st element of the pattern array will be replaced with the 1st element of the replacement array, and the 2nd with the 2nd element of the replacement array, and so on. If the replacement element is not exist, then the relative pattern will be replaced with an empty string.
<?PHP
	$arr=array("PHP","Javascript","Tutorial");
	$pat=array("PHP","Javascript");
	$rep="";
	print_r(str_replace($pat,$rep,$arr));
	//Array ( [0] => [1] => [2] => Tutorial ) 
	$rep=array("Python","JS");
	$cnt=0;
	print_r(str_replace($pat,$rep,$arr,$cnt));
	//Array ( [0] => Python [1] => JS [2] => Tutorial )
	echo "Elements replaced: " . $cnt; //Elements replaced: 2
	$rep=array("Python");
	$cnt=0;
	print_r(str_replace($pat,$rep,$arr,$cnt));
	//Array ( [0] => Python [1] => [2] => Tutorial ) Elements replaced: 2
	echo "Elements replaced: " . $cnt; //Elements replaced: 2
?>