i

PHP Tutorial

Using Filters

Let us see usage of some filters via examples:

1. FILTER_SANITIZE_STRING

$string = "

Hello World!

";

$text = filter_var($string, FILTER_SANITIZE_STRING);

echo $text;

?>

Output will remove the HTML tags from the string.

2. FILTER_VALIDATE_INT

  $num = 100;

if (!filter_var($num, FILTER_VALIDATE_INT) === false) {
    echo("Valid Integer");
} else {
    echo("Integer is not valid");
}
?>

The above code will check if the value is integer or not and the output will be: Valid Integer. But if we set the $num value to 0, this function will return Integer is not valid. To solve this error, use the below code.

$num = 0;

if (filter_var($num, FILTER_VALIDATE_INT) === 0 || !filter_var($num, FILTER_VALIDATE_INT) === false) {
    echo("Valid Integer");
} else {
    echo("Integer is not valid");
}
?>