大网数据广告活动
PHP 语言与运行手册

User Defined Filter

· 52CE 我爱测

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

User Defined Filter

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

FILTER_CALLBACK (int)

This filter delegates the filtering to a user defined function. The callable is passed via the options parameter as the value associated to the 'options' key.

The callback should have the following signature:

function callback(string $value): mixed
value

The value that is being filtered.

Note:

The value returned by the callback will be the value returned by the invoked filter function.

Example #1 Example of using FILTER_CALLBACK to validate a login name

<?php
function validate_login(string $value): ?string
{
    if (strlen($value) >= 5 && ctype_alnum($value)) {
        return $value;
    }
    return null;
}

$login = "val1dL0gin";
$filtered_login = filter_var($login, FILTER_CALLBACK, ['options' => 'validate_login']);
var_dump($filtered_login);

$login = "f&ke login";
$filtered_login = filter_var($login, FILTER_CALLBACK, ['options' => 'validate_login']);
var_dump($filtered_login);
?>

The above example will output:

string(10) "val1dL0gin"
NULL

Note:

As of PHP 8.1.25 and 8.2.12, the structural flags FILTER_REQUIRE_ARRAY, FILTER_FORCE_ARRAY and FILTER_REQUIRE_SCALAR apply to this filter, and FILTER_NULL_ON_FAILURE changes how such a structural failure is reported. In earlier versions all flags were ignored. Filter specific flags are always ignored, and since the return value of the callback is the result, the callback itself cannot fail: no flag turns a false returned by the callback into null or an exception.

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。