PHP Advanced Filters
Validate whether a number is within a range
The following example uses the filter_var() function to validate whether an integer variable is within 1 to 200:
Example
<?php
$int = 122;
$min = 1;
$max = 200;
if (filter_var($int, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min, "max_range"=>$max))) === false) {
echo("Variable value is not within the valid range");
} else {
echo("Variable value is within the valid range");
}
?>
$int = 122;
$min = 1;
$max = 200;
if (filter_var($int, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min, "max_range"=>$max))) === false) {
echo("Variable value is not within the valid range");
} else {
echo("Variable value is within the valid range");
}
?>
Try it Yourself »
Validate an IPv6 address
The following example uses the filter_var() function to validate whether the $ip variable is an IPv6 address:
Example
<?php
$ip = "2001:0db8:85a3:08d3:1319:8a2e:0370:7334";
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) {
echo("$ip"is an IPv6 address");
} else {
echo("$ip"is not an IPv6 address");
}
$ip = "2001:0db8:85a3:08d3:1319:8a2e:0370:7334";
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) {
echo("$ip"is an IPv6 address");
} else {
echo("$ip"is not an IPv6 address");
}
Try it Yourself »
Validate URL - must contain QUERY_STRING (query string)
The following example uses the filter_var() function to validate whether $url contains a query string:
Example
<?php
$url = "http://www.example.com";
if (!filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED) === false) {
echo("$url"is a valid URL");
} else {
echo("$url"is not a valid URL");
}
?>
$url = "http://www.example.com";
if (!filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED) === false) {
echo("$url"is a valid URL");
} else {
echo("$url"is not a valid URL");
}
?>
Try it Yourself »
Remove characters with ASCII value greater than 127
The following example uses the filter_var() function to remove characters with ASCII value greater than 127 from a string, and it can also remove HTML tags:
Example
<?php
$str = "<h1>Hello WorldÆØÅ!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
echo $newstr;
?>
$str = "<h1>Hello WorldÆØÅ!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
echo $newstr;
?>
Try it Yourself »
PHP Filter Reference Manual
You can also visit this site'sPHP Filter Reference Manualto see the specific applications of filters.
The reference manual contains brief descriptions and usage examples of filter parameters!
Other Extensions