本文介绍了字符串替换数组PHP中的所有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在数组中的所有项目中进行字符串替换。我所拥有的是:

$ $ $ $ $ $ $ $ $ $ $'$'$''''= 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不起作用,因为您需要引用,或者使用键:

$ $ $ $ $ $ $ $ $ $ $ $ foreach $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ str_replace(&,& amp;,$ value);
}
unset($ value); //断开最后一个元素的引用

或者:

  foreach($ columns as $ key => $ value){
$ columns [$ key] = str_replace(&,& amp ;,$ value);





尽管在这里没有必要,因为 str_replace code>接受并返回数组。


I would like to do a string replacement in all items in an array. What I have is:

$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']);

How can I achieve this with less code? I thought a foreach statement would work, e.g.:

$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);
}

But it doesn't work.

解决方案

Just do:

$row = str_replace("&", "&", $row);

Note: Your foreach doesn't work because you need a reference, or use the key:

foreach ( $columns as &$value) { // reference
   $value  = str_replace("&", "&", $value);
}
unset($value); // break the reference with the last element

Or:

foreach ($columns as $key => $value){
   $columns[$key]  = str_replace("&", "&", $value);
}

Although it is not necessary here because str_replace accepts and returns arrays.

这篇关于字符串替换数组PHP中的所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 14:30