Replace string in an array with PHP
How can I replace a sub string with some other string for all items of an开发者_Python百科 array in PHP?
I don't want to use a loop to do it. Is there a predefined function in PHP that does exactly that?
How can I do that on keys of array?
Why not just use str_replace without a loop?
$array = array('foobar', 'foobaz');
$out = str_replace('foo', 'hello', $array);
$array = array_map(
function($str) {
return str_replace('foo', 'bar', $str);
},
$array
);
But array_map
is just a hidden loop. Why not use a real one?
foreach ($array as &$str) {
$str = str_replace('foo', 'bar', $str);
}
That's much easier.
This is a very good idea that I found and used successfully:
function str_replace_json($search, $replace, $subject)
{
return json_decode(str_replace($search, $replace, json_encode($subject)), true);
}
It is good also for multidimensional arrays.
If you change the "true" to "false" then it will return an object instead of an associative array.
Source: Codelinks
I am not sure how efficient this is, but I wanted to replace strings in a big multidimensional array and did not want to loop through all items as the array structure is pretty dynamic.
I first json_encode
the array into a string.
Replace all the strings I want (need to use preg_replace
if there are non-English characters that get encoded by json_encode
).
json_decode
to get the array back.
function my_replace_array($array,$key,$val){
for($i=0;$i<count($array);$i++){
if(is_array($array[$i])){
$array[$i] = my_replace_array($array[$i],$key,$val);
}else{
$array[$i]=str_replace($key,$val,$array[$i]);
}
}
return $array;
}
With array_walk_recursive()
function replace_array_recursive( string $needle, string $replace, array &$haystack ){
array_walk_recursive($haystack,
function (&$item, $key, $data){
$item = str_replace( $data['needle'], $data['replace'], $item );
return $item;
},
[ 'needle' => $needle, 'replace' => $replace ]
);
}
$base = array('citrus' => array( "orange") , 'berries' => array("blackberry", "raspberry"), );
$replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry'));
$basket = array_replace_recursive($base, $replacements);
$basket = array_replace($base, $replacements);
精彩评论