filter_var
filter_var
(PHP 5 >= 5.2.0, PHP 7)
filter_var - 用指定的过滤器过滤变量
描述
mixed filter_var ( mixed $variable [, int $filter = FILTER_DEFAULT [, mixed $options ]] )
参数
variable
值过滤。请注意,标量值在被过滤之前会在内部转换为字符串。
filter
要应用的过滤器的ID。该类型的过滤器手册页列出了可用的过滤器。
如果省略,FILTER_DEFAULT
将被使用,这相当于FILTER_UNSAFE_RAW
。这将导致默认情况下不进行过滤。
options
选项的关联数组或标志的按位分隔。如果过滤器接受选项,则可以在数组的“标志”字段中提供标志。对于“回调”过滤器,应传递可调用类型。该回调必须接受一个参数,即要过滤的值,并在过滤/消毒后返回该值。
<?php
// for filters that accept options, use this format
$options = array(
'options' => array(
'default' => 3, // value to return if the filter fails
// other options here
'min_range' => 0
),
'flags' => FILTER_FLAG_ALLOW_OCTAL,
$var = filter_var('0755', FILTER_VALIDATE_INT, $options
// for filter that only accept flags, you can pass them directly
$var = filter_var('oops', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE
// for filter that only accept flags, you can also pass as an array
$var = filter_var('oops', FILTER_VALIDATE_BOOLEAN,
array('flags' => FILTER_NULL_ON_FAILURE)
// callback validate filter
function foo($value)
{
// Expected format: Surname, GivenNames
if (strpos($value, ", ") === false) return false;
list($surname, $givennames) = explode(", ", $value, 2
$empty = (empty($surname) || empty($givennames)
$notstrings = (!is_string($surname) || !is_string($givennames)
if ($empty || $notstrings) {
return false;
} else {
return $value;
}
}
$var = filter_var('Doe, Jane Sue', FILTER_CALLBACK, array('options' => 'foo')
?>
返回值
返回过滤的数据,或者FALSE
过滤器失败。
例子
Example #1 A filter
_
var() example
<?php
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL)
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)
?>
上面的例子将输出:
string(15) "bob@example.com"
bool(false)
← filter_var_array