Php-str_replace cannot traverse replacement see the following code
$ Data = array ('or', 'My ', 'you', 'which', 'love ');
$ Arr = array ('L' => 'K', 'W' => 'Q', 'E' => 'R', 'T' => 'y ', 'M' => 5 );
Foreach ($ data as $ k => $ v ){
Foreach ($ arr as $ key => $ value ){
$ Pattern = $ key;
$ Replacment = $ value;
$ Data [$ k] = str_replace ($ pattern, $ replacment, $ v); // cannot be replaced ??
// $ Data [$ k] = str_replace (array_keys ($ arr), $ arr, $ v );
// $ Data [$ k] = str_replace ('L', 'K', $ v );
}
}
Var_dump ($ data );
?>
Reply to discussion (solution)
I don't know whether the replacement refers to matching all the characters in each character string in data in arr, and replacing them with some. If this is the case, you can directly write it like this:
$ Data [$ k] = str_replace ($ pattern, $ replacment, $ v );
In this sentence, $ v is copied again and changed to $ data [$ k].
$ Data [$ k] = str_replace ($ pattern, $ replacment, $ data [$ k]);
Thank you. I know that writing in this way can achieve the effect of replacement, but my question is, why can't I use foreach to replace it? Where is the error ..
$ Data [$ k] = str_replace ($ pattern, $ replacment, $ v );
$ Data [$ k] is cyclically assigned, and the result of the last assigned value is obtained.
Thank you. I know that writing in this way can achieve the effect of replacement, but my question is, why can't I use foreach to replace it? Where is the error ..
Print $ pattern $ replacement $ data [$ k] In the Loop to see if it is clear.
0 orororororor1 mymymymymy5y2 youyouyouyouyouyou3 whichwhichqhichwhichwhichwhich4 lovekovelovelovrlovelove
This is the loop result I printed, in fact, in foreach. Str_replace has taken effect, but it is replaced later.
Foreach ($ data as $ k => $ v ){
$ V is a copy of $ data [$ k ].
Loop in the internal layer
$ Data [$ k] = str_replace ($ pattern, $ replacment, $ v );
$ V has not changed, so all replications are for the original data, rather than for the result of the previous replacement.
If you write
Foreach ($ data as $ k =>&$ v ){
As you can see, it does work.