Replace string in an array with PHP

后端 未结 6 604
傲寒
傲寒 2020-12-09 17:57

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 t

相关标签:
6条回答
  • 2020-12-09 18:35

    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.

    0 讨论(0)
  • 2020-12-09 18:38

    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 ]
        );
    }
    
    0 讨论(0)
  • 2020-12-09 18:39

    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

    0 讨论(0)
  • 2020-12-09 18:54
    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;
    }
    
    0 讨论(0)
  • 2020-12-09 18:58
    $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.

    0 讨论(0)
  • 2020-12-09 18:59

    Why not just use str_replace without a loop?

    $array = array('foobar', 'foobaz');
    $out = str_replace('foo', 'hello', $array);
    
    0 讨论(0)
提交回复
热议问题