For During this period of time, I was reading the book "PHP and MySQL Web Development" and saw an explanation of str_replace. A small tip was written: You can use arrays to pass in all three of str_replace. But the explanation is relatively simple, so I decided to test the execution results of this function when each parameter is passed into the array.
Function prototype: mixed str_replace(mixed needle, mixed new_needle, mixed haystack[,int &count]);
needle: the string to be replaced, new_needle: the string to be replaced, haystack: operating string, count: number of substitutions [optional parameters]
We focus on testing the execution methods of the first three using arrays:
When neither arrays are used, this function Directly use new_needle to replace all needles and return the replaced string. For example: str_replace("m","n","my name is jim!") returns ny nane is jin!
1. The PHP function str_replace only uses the array for needle.
Example: str_replace(array('m','i'),'n',"my name is jim!"); Return: ny nane ns jnn!
As you can see, the function order Compatibly replaces each string in the array and returns the replaced string.
2. The PHP function str_replace only uses arrays for new_needle.
Example: str_replace('m',array('n','z'),"my name is jim!n") returns: Arrayy naArraye is jiArray!
This replacement comparison Interestingly, if you only use an array for the second parameter, the function will use it as a string Array, replacing all needles with arrays.
3. The PHP function str_replace only uses arrays for haystack.
Example: str_replace("m","n",array("my name is jim!","the game is over!")) The execution result of this statement returns an array, that is, respectively The result after replacing the two strings passed in.
If you output the array content, you will see: ny nane is jin! the gane is over!
4. The PHP function str_replace uses arrays for both needle and new_needle.
Example: str_replace(array("m","i"),array("n","z"),"my name is jim!") Return: ny nane zs jzn!
Looking at the execution results, you can find that if the first two parameters use arrays, the function replaces the strings of each object item in the array, and replaces the first item of needle with the first item of new_needle. And so on.
If the needle array is longer than new_deedle, for example: str_replace(array("m","i","s"),array("n","z"),"my name is jim!"); return :ny nane z jzn! It can be seen that the extra strings in the needle array are replaced with empty strings.
If the new_needle array is longer than needle, for example: str_replace(array("m","i"),array("n","z","x"),"my name is jim!") return ny nane zs jzn! It can be seen that the redundant items of new_needle are ignored.
5. All three parameters of the PHP function str_replace use arrays.
For example: str_replace(array("m","i"),array("n","z"),array("my name is jim!","the game is over ")) The returned array content: ny nane zs jzn! the gane zs over
This is easier to understand. Replace the two strings separately.