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

时间:2016-03-18 14:28:03

标签: php arrays str-replace

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

其中一些位于我要删除的子目录中,例如“ SUB /”。为了优化,这是最好的选择吗?

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

这对我的开发机器来说并不重要,但我打算最终将它从Raspberry Pi上运行,所以我能得到的越多越好。

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

  • 在数组
  • 上使用str_replace
  • Implode,在字符串上使用str_replace,爆炸

2 个答案:

答案 0 :(得分:1)

正如@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);

答案 1 :(得分:1)

$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.
相关问题