批量字符串替换数组的最佳方法


Optimal way to bulk string replace an array

>我有一个大约 1500 个条目的文件路径数组。

其中一些位于我要删除的子目录中,例如"SUB/"。 为了优化,哪个是最佳选择?

  • Foreach ($key=>$val)和字符串更新$array[$key] = str_replace("_SUB_/","",$val);
  • 与上面相同,但执行 if/then 以仅在字符串以"SUB/"开头时才运行str_replace
  • 将数组内爆为单个字符串,在该字符串上运行str_replace,然后将其分解回数组
  • 我没有想到的其他事情

这些在我的开发机器上都不重要,但我打算最终从 Raspberry Pi 上运行它,所以我能得到的越理想越好。


更新:我不知道str_replace直接在数组上工作,在这种情况下,只有两个选项

  • 在阵列上使用str_replace
  • 内爆,在绳子上使用str_replace,爆炸
$array = str_replace("_SUB_/","",$array);

http://php.net/manual/es/function.str-replace.php

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
subject
The string or array being searched and replaced on, otherwise known as the haystack.
If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.

正如@jszobody所说,str_replace也可以使用数组(我不知道的事情!

$array = str_replace("_SUB_/","",$array);

或者,array_map() 允许您将函数应用于数组的每个项目:

function replace_sub($n)
{
    return str_replace("_SUB_/", "", $str);
}
$result = array_map("replace_sub", $array);