Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

$f = function ($string) { return preg_replace('~[^a-z]~i', '', $string); };
$myValues = array_map($f, $myValues);

I'd use array_map and a regex, personally.

     $array = Array("abc123", "123jkl", "abc123def");
     $array = array_map("preg_replace", 
                         array_fill(0, count($array), '/[^a-z]*/'), 
                         array_fill(0, count($array), ''),
                         $array );

scanning == regexps

As with other answers this one is again based on mastering regular expressions, which is essentially THE basic character scanning (and parsing) technique all those validators are built upon. The idea about validators/filters is to define/guess/cover as many reasonable classes of strings (regexps) as possible. (Plus there is an optimization speed up for trivial classes like [0-9]* or [a-z]* - no need to go via standard perl-compatible)

filter_var_array and callbacks

As a quick remark: indeed, things like FILTER_VALIDATE_REGEXP did not work for me either...

filter_var_array & co. is relatively new practice, but if you must then fallback to whatever custom FILTER_CALLBACK works in the following form:

<?php
error_reporting(E_ALL | E_STRICT);

function handle($value) {
    return preg_replace('/[^a-z]/', '', $value);
}

$data = array(
    'testfield'    => array('22', 'foo', 'bar', '42'),
);

$args = array(
    'testfield'    => array('filter'    => FILTER_CALLBACK,
                            'options'   => 'handle'
        ),
    );

$result = filter_var_array($data, $args);

var_dump($result);

and produces

array(1) {
  ["testfield"]=>
  array(4) {
    [0]=>
    string(0) ""
    [1]=>
    string(3) "foo"
    [2]=>
    string(3) "bar"
    [3]=>
    string(0) ""
  }
}

Perhaps no better than foreach, but it is an "other way":

array_walk($a, function(&$e) {
    $e = preg_replace('/[^a-z]/', '', $e);
});

(Requires PHP 5.3 if you use this anonymous function syntax, also called a "closure".)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top