@ 2020-07-09T04:33:12Z <?php
function validate_length ($options = ['min_length' => 1, 'max_length' => null], $filters = null)
{
return static function ($value = null) use ($options, $filters) {
$len = strlen($value);
if (isset($options['min_length']) && $len < $options['min_length']) {
return false;
}
if (isset($options['max_length']) && $len > $options['max_length']) {
return false;
}
if (null !== $filters) {
return filter_var($value, ...$filters); //php 5.6+ array spread operator
}
return $value;
};
}
$a = [
'a' => 'value',
'b' => '',
'c' => 'a@example.com',
'd' => 'This& is a 🍕 Test',
];
$email_filter = [FILTER_VALIDATE_EMAIL, ['flags' => FILTER_FLAG_EMAIL_UNICODE]];
$string_filter = [FILTER_SANITIZE_STRING, ['flags' => FILTER_FLAG_ENCODE_AMP | FILTER_FLAG_STRIP_HIGH]];
$result = filter_var_array ($a, [
'a' => ['filter' => FILTER_CALLBACK, 'options' => validate_length(['max_length' => 4])],
'b' => ['filter' => FILTER_CALLBACK, 'options' => validate_length(['min_length' => 1])],
'c' => ['filter' => FILTER_CALLBACK, 'options' => validate_length(['min_length' => 1, 'max_length' => 20], $email_filter)],
'd' => ['filter' => FILTER_CALLBACK, 'options' => validate_length(['min_length' => 1], $string_filter)],
]);
var_dump($result);
Enable javascript to submit You have javascript disabled. You will not be able to edit any code.
Output for 8.1.0 - 8.1.30 , 8.2.0 - 8.2.25 , 8.3.0 - 8.3.13 Deprecated: Constant FILTER_SANITIZE_STRING is deprecated in /in/83uXu on line 31
array(4) {
["a"]=>
bool(false)
["b"]=>
bool(false)
["c"]=>
string(13) "a@example.com"
["d"]=>
string(20) "This& is a Test"
}
Output for 7.2.0 - 7.2.34 , 7.3.0 - 7.3.33 , 7.4.0 - 7.4.33 , 8.0.0 - 8.0.30 array(4) {
["a"]=>
bool(false)
["b"]=>
bool(false)
["c"]=>
string(13) "a@example.com"
["d"]=>
string(20) "This& is a Test"
}
preferences:dark mode live preview
40.2 ms | 408 KiB | 5 Q