Replace string in an array with PHP
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