Easy Tutorial
❮ Func String Mb_Substr Func Filesystem Fileatime ❯

PHP Advanced Filters


Check if a Number is Within a Specified Range

The following example uses the filter_var() function to check if an INT variable is within the range of 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 legal range");
} else {
    echo("Variable value is within the legal range");
}
?>

Check for IPv6 Address

The following example uses the filter_var() function to check if 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");
}
?>

Check for URL - Must Contain QUERY_STRING (Query String)

The following example uses the filter_var() function to check if $url contains a query string:

Example

<?php
$url = "http://www.tutorialpro.org";
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");
}
?>

Remove Characters with ASCII Value Greater Than 127

The following example uses the filter_var() function to remove characters with ASCII values 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;
?>

PHP Filter Reference Manual

You can also visit the PHP Filter Reference Manual on our site to see specific applications of filters.

The reference manual includes a brief explanation of filter parameters and usage examples!

❮ Func String Mb_Substr Func Filesystem Fileatime ❯