mvanvu/php-filter

PHP 输入过滤器包

1.0.5 2021-03-09 14:14 UTC

This package is auto-updated.

Last update: 2024-09-09 21:37:52 UTC


README

通过Composer安装

{
	"require": {
		"mvanvu/php-filter": "~1.0"
	}
}

或者,通过命令行

composer require mvanvu/php-filter

用法

use MaiVu\Php\Filter;

// Syntax
Filter::clean($source, $type);

// Example
$source = '<h1>Hello World!</h1>';

// Return 'Hello World!'
$filtered = Filter::clean($source, 'string');

// Source array
$source = [
	'<h1>Hello World!</h1>',
	'<h1>Hello VietNam!</h1>',
];

// Return ['Hello World!', 'Hello VietNam!']
$filtered = Filter::clean($source, 'string:array');

// Multi-type
$source = '  <h1>Hello World!</h1>  ';

// Return 'Hello World!'
$filtered = Filter::clean($source, ['string', 'trim']);

添加新的自定义规则

use MaiVu\Php\Filter;
Filter::setRule('custom', function($value) {
    return $value . ' is filtered by a Closure';
});

$source = 'Hello World!';

// Return 'Hello World! is filtered by a Closure'
$filtered = Filter::clean($source, 'custom');

// The same above
Filter::clean($source, function($value) {
    return $value . ' is filtered by a Closure';
});

扩展过滤器

use MaiVu\Php\Filter;

class CustomFilter extends Filter
{
	public static function arrayInteger($value)
	{
		return static::clean($value, 'int:array');
	}
}

// Return '[1, 2, 3]'
echo '<pre>' . print_r(CustomFilter::clean(['1abc2', '2b', 3], 'arrayInteger'), true) . '</pre>';

过滤器类型

  • int
  • uint (无符号整型)
  • float, double
  • ufloat, udouble (无符号浮点)
  • boolean
  • alphaNum (字母数字字符串)
  • base64
  • string (无HTML标签)
  • email
  • url
  • slug (无斜杠的URL别名)
  • path (带斜杠的URL别名)
  • unset (返回NULL值)
  • jsonEncode
  • jsonDecode
  • yesNo, yes|no (返回'Y'或'N')
  • YES|NO (返回'YES'或'NO')
  • 1|0 (返回1或0)
  • inputName (正则表达式 /[^a-zA-Z0-9_]/)
  • unique (数组唯一)
  • basicHtml

默认回退值

if (isset(static::$rules[$type]))
    {
        $result = call_user_func_array(static::$rules[$type], [$value]);
    }
    elseif (is_callable($type))
    {
	    $result = call_user_func_array($type, [$value]);
    }
    elseif (function_exists($type))
    {
        $result = $type($value);
    }
    else
    {
        $result = $value;
    }
}