Search code examples
phparrayssanitize

php use filter_var_array to strip anything but a-z


I am trying to remove all characters from my array values except for the a-z characters using the filter_var_array function.

I tried applying multiple filters but unfortunatly none of them did the trick for me, is there any other way to do this using this function or am I forced to use something like regex in a foreach loop to do this?


Solution

  • preg_replace() already works quite naturally on an array. This removes all non-alphas from an array of strings:

    $array = preg_replace('/[^a-z]/i', '', $array);
    

    Example:

    $a = array('1111A55b999c0000','111111def9999999','0000000g88888hi8888888');
    $a = preg_replace('/[^a-z]/i', '', $a);
    assert($a == array('Abc','def','ghi'));
    

    I'm guessing you may want case-insensitivity. If you truly want to strip out uppercase letters as well, just remove the i.