filter_var
Description
The filter_var of Filter for PHP filters a variable with a specified filter.
Syntax
filter_var( mixed $value, int $filter = FILTER_DEFAULT, array|int $options = 0 ): mixed
Parameters
value
Value to filter. Note that scalar values are converted to string internally before they are filtered.
filter
The ID of the filter to apply. The Types of filters manual page lists the available filters.
If omitted, FILTER_DEFAULT will be used, which is equivalent to FILTER_UNSAFE_RAW. This will result in no filtering taking place by default.
options
Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array. For the "callback" filter, callable type should be passed. The callback must accept one argument, the value to be filtered, and return the value after filtering/sanitizing it.
Return
Returns the filtered data, or false if the filter fails.
Examples
1 · value
<? $value = "osbo.com"; $return = filter_var($value); echo $return;
osbo.com
2 · filter
<? $value = "https://osbo.com"; $filter = FILTER_VALIDATE_URL; $return = filter_var($value, $filter); echo $return;
https://osbo.com
3 · options
<? $value = "https://osbo.com/path?query"; $filter = FILTER_VALIDATE_URL; $options = FILTER_FLAG_PATH_REQUIRED | FILTER_FLAG_QUERY_REQUIRED; $return = filter_var($value, $filter, $options); echo $return;
https://osbo.com/path?query
4
<? $value = "0755"; $filter = FILTER_VALIDATE_INT; $options = array( "options" => array( "default" => 3, "min_range" => 0 ), "flags" => FILTER_FLAG_ALLOW_OCTAL, ); $return = filter_var($value, $filter, $options); echo $return;
493
5
<? $value = "invalid"; $filter = FILTER_VALIDATE_BOOLEAN; $options = FILTER_NULL_ON_FAILURE; $return = filter_var($value, $filter, $options); var_export($return);
NULL
6
<? $value = "invalid"; $filter = FILTER_VALIDATE_BOOLEAN; $options = array("flags" => FILTER_NULL_ON_FAILURE); $return = filter_var($value, $filter, $options); var_export($return);
NULL
7
<? function myfunction($myvalue) { return $myvalue; } $value = "myvalue"; $filter = FILTER_CALLBACK; $options = array("options" => "myfunction"); $return = filter_var($value, $filter, $options); echo $return;
myvalue