Yesterday, while writing an API to retrieve WordPress theme information, I needed to replace the English content in style.css, so I used the string replacement function str_replace(). At first, I used more than ten consecutive str_replace() functions before getting everything replaced.

Later, an expert told me that the parameters of the str_replace() function could be set as arrays to perform batch replacements in order. I tried it, and it really only took one str_replace() function to do the job. Below, I will share my experience.

str_replace()

The following mainly explains four cases of the str_replace() function.

Using an array only for the values to be replaced

Example

<?php
echo str_replace(array('w','m'),'x','www.ikxin.com');
?>

Output: xxx.ikxin.cox

As you can see, the function sequentially replaces each string in the array and returns the replaced string.

Using an array only for the replacement values

Example

<?php
echo str_replace('i',array('w','m'),"www.ikxin.com");
?>

Output: www.ArraykxArrayn.com

This replacement is rather interesting. If an array is used only for the second parameter, the function treats it as the string Array, replacing all the values to be replaced with Array.

Using an array only for the values-to-be-replaced parameter

Example

<?php
echo str_replace('w','n',array('www.ikxin.com','www.baidu.com'));
?>

The result of executing this statement is an array, containing the results after each of the two passed strings has been replaced.

Using arrays for both the replacement values and the values to be replaced

Example

<?php
echo str_replace(array("m","w"),array("h","n"),"www.ikxin.com");
?>

Output: nnn.ikxin.coh

If arrays are used for both of the first two parameters, the function replaces the strings in the corresponding array items. Therefore, the first item of the values to be replaced is replaced with the first item of the replacement values, and so on.