views:

300

answers:

1

I have been toying with PHP filter library. I liked it but I am unable to perform a simple filter function. I essentially want to invalidate those values in my input array that are strings and which are longer than certain value. Is there a way to do this like,

$data = array('input_string_array' => array('aaa', 'abaa', 'abaca'));
$args = array(
    'component'    => array('filter'    => FILTER_DEFAULT,
                            'flags'     => FILTER_REQUIRE_ARRAY, 
                            'options'   => array('min_length' => 1, 'max_length' => 10)
                           )
);

var_dump(filter_var_array($data, $args));

I tried this and its giving me error. because presumably there is no min_length/max_length option available. But then how to implement this? Also is there a place where it is mentioned about all such options like max_range, min_range, regexp.

Also I had another doubt, in filters, in FILTER_CALLBACK filter. I wanted to know if there is a way to pass a parameter other than the data to the called function? something like this,

echo filter_var($string, FILTER_CALLBACK, array("options"=> array("lengthChecker", "5")));

Thanks a lot for the help.

+3  A: 

Unless there's a better, more direct filter+option you can use FILTER_VALIDATE_REGEXP

$data = array('input_string_array' => array('', 'aaa', 'abaa', 'abaca'));
$args = array(
  'input_string_array' => array(
    'filter' => FILTER_VALIDATE_REGEXP,
    'flags'     => FILTER_REQUIRE_ARRAY|FILTER_NULL_ON_FAILURE,
    'options'   => array('regexp'=>'/^.{1,3}$/')
  )
);
var_dump(filter_var_array($data, $args));

prints

array(1) {
  ["input_string_array"]=>
  array(4) {
    [0]=>
    NULL
    [1]=>
    string(3) "aaa"
    [2]=>
    NULL
    [3]=>
    NULL
  }
}

To get rid of the NULL elements you can use e.g. array_filter().

VolkerK