Trel
Trel

Reputation: 353

Optimal way to bulk string replace an array

I have an array about 1500 entries worth of file paths.

Some of them are in a sub directory which I want to remove, say "SUB/". For optimization's sake, which is the best option?

None of this matters much on my dev machine, but I'm intending to ultimately run it off a Raspberry Pi, so the more optimal I can get it, the better.


Update: I was not aware that str_replace worked directly on arrays, in that case, just two options then

Upvotes: 0

Views: 530

Answers (2)

Maxi Schvindt
Maxi Schvindt

Reputation: 1462

$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.

Upvotes: 2

Egg
Egg

Reputation: 1769

As @jszobody says, str_replace will work with arrays too (something I didn't know!):

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

Alternatively, array_map() allows you to apply a function to each item of an array:

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

Upvotes: 1

Related Questions