replace string in an array with php

泪湿孤枕 提交于 2019-12-17 18:55:50

问题


How can I replace a sub string with some other string for all items of an 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?

Edited: Thank you for your reply,one more question,how can i do that on keys of array?


回答1:


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




回答2:


Why not just use str_replace without a loop?

$array = array('foobar', 'foobaz');
$out = str_replace('foo', 'hello', $array);



回答3:


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




回答4:


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 their are non-english characters that get encoded by json_encode)

json_decode to get the array back.




回答5:


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;
}


来源:https://stackoverflow.com/questions/4977048/replace-string-in-an-array-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!