本文共 2028 字,大约阅读时间需要 6 分钟。
名称 | id | 说明 | 选项options |
回调过滤器(callback) | 1024 | 调用自定义函数来过滤数据 | callable函数或方法 |
回调函数必须接受一个待过滤的值,并返回过滤后的值,回调函数有四种实现方式。
第一种是直接定义回调函数,并在使用过滤器函数时,将回调过滤器的options设置为自定义的回调函数。
'trimString',);var_dump(filter_var('abc ',FILTER_CALLBACK,$args));?>
第二种是在使用过滤器函数时,将回调过滤器的options直接设置为回调函数。
function ($value){return trim($value);},);var_dump(filter_var('abc ',FILTER_CALLBACK,$args));?>
第三种是通过闭包实现调用回调函数来传递其他参数。
trimString(array("character_mask"=>'a..c ')),);var_dump(filter_var('abcd ',FILTER_CALLBACK,$args));?>
第四种是使用类中的函数作为回调函数,可以用来将多个过滤器回调函数集中到一起。
" \t\n\r\0\x0B"); public function __construct(array $options=array()){ $this->options = $options; } private function get_options(array $defaults){ return array_merge($defaults, $this->options); } function trimString($value){ $ops=$this->get_options($this->defaults); if(key_exists('character_mask',$ops)){ return trim($value,$ops['character_mask']); } return trim($value); } function ltrimString($value){ $ops=$this->get_options($this->defaults); if(key_exists('character_mask',$ops)){ return ltrim($value,$ops['character_mask']); } return ltrim($value); } function rtrimString($value){ $ops=$this->get_options($this->defaults); if(key_exists('character_mask',$ops)){ return rtrim($value,$ops['character_mask']); } return rtrim($value); } }$trim_args=array( 'options'=>array( new TrimFilter(array('character_mask'=>" a")),TRIMSTRING ));$ltrim_args=array( 'options'=>array( new TrimFilter(array('character_mask'=>" a")),LTRIMSTRING ));$rtrim_args=array( 'options'=>array( new TrimFilter(),RTRIMSTRING ));$str="abcd ";var_dump(filter_var($str,FILTER_CALLBACK,$trim_args));var_dump(trim($str," a"));var_dump(filter_var($str,FILTER_CALLBACK,$ltrim_args));var_dump(ltrim($str," a"));var_dump(filter_var($str,FILTER_CALLBACK,$rtrim_args));var_dump(ltrim($str));?>
转载地址:http://lykkb.baihongyu.com/