问题描述
我想在数组中的所有项目中进行字符串替换。我所拥有的是:
$ $ $ $ $ $ $ $ $ $ $'$'$''''= str_replace(&,& amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; ,$ row ['c1']);
$ row ['c2'] = str_replace(&,& amp;,$ row ['c2']);
$ row ['c3'] = str_replace(&,& amp;,$ row ['c3']);
$ row ['c4'] = str_replace(&,& amp;,$ row ['c4']);
$ row ['c5'] = str_replace(&,& amp;,$ row ['c5']);
$ row ['c6'] = str_replace(&,& amp;,$ row ['c6']);
$ row ['c7'] = str_replace(&,& amp;,$ row ['c7']);
$ row ['c8'] = str_replace(&,& amp;,$ row ['c8']);
$ row ['c9'] = str_replace(&,& amp;,$ row ['c9']);
$ row ['c10'] = str_replace(&,& amp;,$ row ['c10']);
如何用较少的代码实现这一点?我认为一个foreach语句可以工作,例如:
$ $ $ $ $ $ $ $ $ row $ array $ row ['c1'],$ row [ 'c2'],$ row ['c7'],$ row ['c4'],$ row ['c5'],$ row ['c6'],$ row ['c8'] '],$ row ['c9'],$ row ['c10']);
$ b foreach($ columns为$ value){
$ value = str_replace(&,& amp;,$ value);
}
但是不行。
$ row = str_replace(& amp; ;,&,$ row);
注意:您的foreach不起作用,因为您需要引用,或者使用键: 或者: 尽管在这里没有必要,因为 I would like to do a string replacement in all items in an array. What I have is: How can I achieve this with less code? I thought a foreach statement would work, e.g.: But it doesn't work. Just do: Note: Your foreach doesn't work because you need a reference, or use the key: Or: Although it is not necessary here because 这篇关于字符串替换数组PHP中的所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
$ $ $ $ $ $ $ $ $ $ $ $ foreach $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ str_replace(&,& amp;,$ value);
}
unset($ value); //断开最后一个元素的引用
foreach($ columns as $ key => $ value){
$ columns [$ key] = str_replace(&,& amp ;,$ value);
str_replace code>接受并返回数组。
$row['c1'] = str_replace("&", "&", $row['c1']);
$row['c2'] = str_replace("&", "&", $row['c2']);
$row['c3'] = str_replace("&", "&", $row['c3']);
$row['c4'] = str_replace("&", "&", $row['c4']);
$row['c5'] = str_replace("&", "&", $row['c5']);
$row['c6'] = str_replace("&", "&", $row['c6']);
$row['c7'] = str_replace("&", "&", $row['c7']);
$row['c8'] = str_replace("&", "&", $row['c8']);
$row['c9'] = str_replace("&", "&", $row['c9']);
$row['c10'] = str_replace("&", "&", $row['c10']);
$columns = array($row['c1'], $row['c2'], $row['c3'], $row['c4'], $row['c5'], $row['c6'], $row['c7'], $row['c8'], $row['c9'], $row['c10']);
foreach ( $columns as $value){
$value = str_replace("&", "&", $value);
}
$row = str_replace("&", "&", $row);
foreach ( $columns as &$value) { // reference
$value = str_replace("&", "&", $value);
}
unset($value); // break the reference with the last element
foreach ($columns as $key => $value){
$columns[$key] = str_replace("&", "&", $value);
}
str_replace
accepts and returns arrays.