We were reading the book "PHP and MySQL Web Development" during the actual period and saw an explanation of the PHP function str_replace. A small tip was written: The three functions of str_replace can be Use an array to pass in, but the explanation is relatively simple, so I decided to test the execution results of the function when each parameter is passed into the array.
Function prototype: mixed str_replace(mixed needle, mixed new_needle, mixed haystack[,int &count]);
needle: string to be replaced, new_needle: string for replacement, haystack: operation String, count: number of replacements [optional parameters]
We focus on testing the first three execution methods when using arrays:
When no array is used, the PHP function str_replace directly uses new_needle to replace all needle and return the replaced string. For example: str_replace("m","n","my name is jim!") returns ny nane is jin!
1. Only use arrays for needle.
Example: str_replace(array('m','i'),'n',"my name is jim!");Return: ny nane ns jnn!
As you can see , the function sequentially replaces each string in the array and returns the replaced string.
2. Only use arrays for new_needle.
PHP function str_replace example: str_replace('m',array('n','z'),"my name is jim!n") returns: Arrayy naArraye is jiArray!
This replacement is more interesting. 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. Only use 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. Use 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 use arrays.
Example of PHP function str_replace: str_replace(array("m","i"),array("n","z"),array("my name is jim!","the The array content returned by game is over")): ny nane zs jzn! the gane zs over
This is easier to understand. Replace the two strings separately.