PHP filter_var() Function

The filter_var function in PHP is used to filter and validate data. It is part of the filter extension and is used to sanitize and validate various types of data such as email addresses, URLs, IP addresses, and integers.
The function has the following syntax:

1)Validating an Email Address:-

Example :-

<?php 

$email = "example@example.com";

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "This email address is valid.";
} else {
    echo "This email address is invalid.";
}

?>

In this example, the filter_var function is used to check if the given email address is valid.
If it is, the script outputs that the email address is valid; otherwise, it indicates the email address is invalid.

2)Sanitizing a String

Example :-

$string = "<h1>Hello World!</h1>";

$sanitized_string = filter_var($string, FILTER_SANITIZE_STRING);

echo $sanitized_string;

In this example, the filter_var function is used to remove HTML tags from the input string. The output will be Hello World!.

3)Sanitizing an Integer :-

Example :-

$int = "123abc";

$sanitized_int = filter_var($int, FILTER_SANITIZE_NUMBER_INT);

echo $sanitized_int; // Output: 123

In this example, the filter_var function is used to remove all characters except digits, plus and minus signs, from the input string. The output will be 123.

These examples show how filter_var can be a powerful and flexible function for handling various types of data sanitization and validation in PHP.

Also Read:-

Laravel Events and Listeners

Exploring the Power of the the_content() Function in WordPress

Also Visit:-

https://inimisttech.com/

Leave a Reply