See the following code
$data = Array (' or ', ' my ', ' I ', ' 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)
Do not know the landlord said the replacement refers to the data inside each string appears in the characters are to arr inside to match, and some replacement. If that's the case, just write it this way:
$data [$k] = Str_replace ($pattern, $replacment, $v);
This sentence inside $v re-copied, replaced by $data[$k]
$data [$k] = Str_replace ($pattern, $replacment, $data [$k]);
Thank you, I know it can be replaced by this kind of writing, but my question is why can't I replace it with a foreach? Where's the mistake?
$data [$k] = Str_replace ($pattern, $replacment, $v);
$data [$k] is the value of the loop, taking the result of the last assignment.
Thank you, I know it can be replaced by this kind of writing, but my question is why can't I replace it with a foreach? Where's the mistake?
You print the $pattern $replacement $data [$k] in the loop to see if it's clearer.
0 orororororor1 mymymymymy5y2 youyouyouyouyouyou3 whichwhichqhichwhichwhichwhich4 lovekovelovelovrlovelove
Landlord this is my printed out of the loop results, in fact, in foreach. Str_replace has come into effect, but is replaced by the back, so you feel no replacement
foreach ($data as $k = = $v) {
The $v in is a copy of the $data [$k]
In the inner loop
$data [$k] = Str_replace ($pattern, $replacment, $v);
$v does not change, so all substitutions are to the original data, not to the last substitution result
If you write
foreach ($data as $k = & $v) {
As you can see, it does work.