PHP Advanced Filter


Detect if a number is in a range

The following example filter_var () function to detect whether an INT-type variable is between 1 and 200:

<?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 values are not within the legal limits");
} else {
echo ("variable values are within the legal limits");
}
?>

Try it out . . .

Detect the IPv6 address

The following example filter_var () function to detect whether $ip variable is an IPv6 address:

<?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 not an IPv6 address");
}
?>

Try it out . . .

Detection URL - must contain QUERY_STRING (query string)

The following instance uses filter_var() function to detect whether $url contains a query string:

<?php
$url = "http://www.w3cschool.cn";

if (!filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED) === false) {
echo ("$url is a legitimate URL");
} else {
echo ("$url is not a legitimate URL");
}
?>

Try it out . . .

Remove characters with ANCII values greater than 127

The following instance uses filter_var() function to remove characters in a string with an ASCII value greater than 127, as well as HTML tags:

<?php
$str = "<h1>Hello WorldÆØÅ!</h1>";

$newstr = filter_var($str, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
echo $newstr;
?>

Try it out . . .

PHP filter reference manual

You can also view the specific application of the filter by visiting the PHP filter reference manual on this site.

The reference manual contains a brief description of the filter parameters and examples of their use!