indgy / philter
无依赖的流畅输入清理器
0.1.5
2023-01-25 12:05 UTC
Requires
- php: ^7.1|^8.0
README
PHP流畅输入清理器。
Philter接受不受信任的输入,通过一些过滤器传递,然后将其返回给您。它不是验证的替代品。
安装
将src/Philter.php
文件复制到您的项目中,或使用composer安装
composer require indgy/philter
入门
创建一个新的Philter实例,传入不受信任的输入,然后组合过滤器以传递不受信任的输入,最后调用toBool()
、toFloat()
、toInt()
或toString()
以获取过滤并现在受信任的输入。
use \Indgy\Philter; $f = new Philter($unsafe_input); $str = $f->in(['safe','string','options']) ->default('safe') ->toString();
还有一个便捷的快捷函数来返回一个新的Philter实例
use function \Indgy\philter; $str = philter($unsafe_input) ->in(['safe','string','options']) ->default('safe') ->toString();
可用过滤器
allow(String $chars)
- 只允许$chars中的字符
alpha()
- 只允许a-z
alphanum()
- 只允许a-z和0-9
ascii()
- 只允许ASCII字符(32-127),尽可能转写
between(Int $min, Int $max)
- 允许介于min和max(包括)之间的值
contains(String $match)
- 允许包含$match的值
cut(Int $length)
- 截取到$length长度的字符串
digits()
- 只允许0-9
in(Array $items)
- 如果在$items中允许
max(Int $max)
- 如果小于或等于$max允许
min(Int $min)
- 如果大于或等于$min允许
numeric()
- 如果是数字允许,例如货币字符串
trim()
- 从开头和结尾删除字符 (另请参阅ltrim()
和rtrim()
)
utf8()
- 转换为UTF-8,尽可能转写
有关过滤器的更多详细信息,请参阅参考。
自定义过滤器
使用带有闭包的apply()
方法定义自定义过滤器。闭包将传递当前输入值并期望返回它或null。
philter('Here we go.. ')->apply(function($v) { // do your thing here $v = $v.= 'I was philtered'; // always return $v or null return $v; })->toString();