批量字符串替换数组的最佳方法
Optimal way to bulk string replace an array
我有一个大约 1500 个文件路径条目的数组。
其中一些位于我要删除的子目录中,比如“SUB/”。为了优化,哪个是最好的选择?
Foreach ($key=>$val)
和字符串更新 $array[$key] = str_replace("_SUB_/","",$val);
- 与上面相同,但如果字符串以“SUB/”开头,则只对 运行 str_replace 执行 if/then
- 将数组分解为单个字符串,运行 str_replace 在该字符串上,然后将其分解回数组
- 我没有想到的其他事情
None 这在我的开发机器上很重要,但我打算最终 运行 它关闭 Raspberry Pi,所以我能得到它越优化,更好。
更新:我不知道 str_replace 直接在数组上工作,在那种情况下,只有两个选择
- 在数组
上使用 str_replace
- 内爆,在字符串上使用 str_replace,爆炸
正如@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);
$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.
我有一个大约 1500 个文件路径条目的数组。
其中一些位于我要删除的子目录中,比如“SUB/”。为了优化,哪个是最好的选择?
Foreach ($key=>$val)
和字符串更新$array[$key] = str_replace("_SUB_/","",$val);
- 与上面相同,但如果字符串以“SUB/”开头,则只对 运行 str_replace 执行 if/then
- 将数组分解为单个字符串,运行 str_replace 在该字符串上,然后将其分解回数组
- 我没有想到的其他事情
None 这在我的开发机器上很重要,但我打算最终 运行 它关闭 Raspberry Pi,所以我能得到它越优化,更好。
更新:我不知道 str_replace 直接在数组上工作,在那种情况下,只有两个选择
- 在数组 上使用 str_replace
- 内爆,在字符串上使用 str_replace,爆炸
正如@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);
$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.