Search code examples
phploopsreplaceordinal

Remove unwanted characters from all elements in an array


I have this function that strips illegal characters and it works fine.

This is the code.

<?php

function fix_output($value, $key){
    $new_array = array();
    $newstr = '';
    $good[] = 9;  #tab
    $good[] = 10; #nl
    $good[] = 13; #cr
    for($a=32;$a<127;$a++){
        $good[] = $a;
    }
    $len = strlen($value);
    for($b=0;$b < $len; $b++){
        if(in_array(ord($value[$b]), $good)){
            $newstr .= $value[$b];
        }//fi
    }//rof
    $new_array[$key] = $newstr;
    return $new_array;
}

$array = array();
$array['references1'] = 'Foo1 ◻◻◻◻◻◻◻◻◻◻◻◻';
$array['references2'] = 'Foo2 ◻◻◻◻◻◻◻◻◻◻◻◻';

array_walk($array,"fix_output");

print_r($array);

I want to use the PHP function array_walk but when I use print_r($array) it didn't strip the illegal characters. What seems to be the problem with this? Any idea would be of help! Please point out the things that are unclear!


Solution

  • array_walk has the option to let you pass the value by reference. This is what you want to do. See the & in-front of $value:

    <?php
    
    function fix_output(&$value, $key) {
        $good = array_merge(range(32, 127), [
            9,   // tab
            10,  // nl
            13   // cr
        ]);
        $value = join("", array_map(
            "chr", 
            array_intersect(
                array_map("ord", str_split($value)), 
                $good
            )
        ));
    }
    
    $array = array();
    $array['references1'] = 'Foo1 ◻◻◻◻◻◻◻◻◻◻◻◻';
    $array['references2'] = 'Foo2 ◻◻◻◻◻◻◻◻◻◻◻◻';
    
    array_walk($array,"fix_output");
    
    print_r($array);
    

    Now your output is:

    Array
    (
        [references1] => Foo1 
        [references2] => Foo2 
    )
    

    I changed the implementation to use more of the array_* functions so you can see how powerful it can be if you combine them. Also not how you can use range() to build the initial good array (also check array_fill_keys).