Using the PHP Function str_replace( ) to Batch Replace Text Content

6,755 0

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 to complete the replacements.

Later, an expert told me that the parameters of the str_replace() function could be set as arrays, allowing batch replacement in order. I tried it, and it really worked with just one str_replace() function. Below, I’ll share my experience.

str_replace()

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

Using an array only for the values to be replaced

Example

PHP
<?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
<?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 and replaces all the values to be replaced with Array.

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

Example

PHP
<?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 replacing the two input strings respectively.

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

Example

PHP
<?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 elements. Therefore, the first value to be replaced is replaced with the first replacement value, and so on.

Comments

(0)

No comments yet. Start the conversation.

Leave a comment