i

PHP Tutorial

Filters Advanced

There are some advanced applications of these filters that we can use in PHP. Some of the examples are as below:

1. Validating an Integer within a range

$num = 143;
$min = 1;
$max = 200;

if (filter_var($num, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min, "max_range"=>$max))) === false) {
    echo("Variable value not in the required range");
} else {
    echo("Variable value is in the required range");
}
?>

In the above code, if the value of $num will be between the $min and $max range, then output will be the variable value is in required range else variable value not in the required range.

2. Query String Required

$url = "https://www.freekygreeks.com";

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

In above code, if the $url is having only characters and numbers then the output will be $url is having query string else $url is not having a query string.

3. Remove Characters with ASCII value>127

$text = "

Welcome to PHP FiltersÆØÅ!

";

$result = filter_var($text, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
echo $result;
?>

The above code will remove HTML tags and characters not in A-Z and 0-9.