filter_var (var, filtername, options)Parameters : This function takes three parameters and described below:
- Disinfect the line:
In the example below, we clear the line Example: -$str
=
"
GeeksforGeeks! < / h1 > "
;
$newstr
= filter_var (
$str
, FILTER_SANITIZE_STRING);
echo
$newstr
;
?>
GeeksforGeeks!
- Check for an integer:In the example below, the filter_var() function is used to check if the variable $int is an integer. If $int is an integer, the output of the code below will look like "Integer is valid". If $int is not an integer, the output is: "Integer is not valid":Example: -
$int
= 200;
if
(filter_var (
$int
, FILTER_VALIDATE_INT) === 0 ||
! filter_var (
$int
, FILTER_VALIDATE_INT) === false)
{
echo
(
"Integer is valid"
);
}
else
{
echo
(
" Integer is not valid "
);
}
?>
Integer is valid
- Check the IP address:
The following example uses the filter_var() function to check if the $ip variable is a valid IP address: Example: -$ip
=
"129.0.0.1"
;
if
(! filter_var (
$ip
, FILTER_VALIDATE_IP) === false) {
echo
(
" $ip is a valid IP address "
);
}
else
{
echo
(
"$ip is not a valid IP address"
);
}
?>
129.0. 0.1 is a valid IP address
- Sanitize and validate an email address:
In the following example, the filter_var() function first removes all invalid characters from the $variable email and then checks if it is a valid email address: Example: -$email
=
"[email protected]"
;
// Remove all invalid characters from email
$email
= filter_var (
$email
, FILTER_SANITIZE_EMAIL);
// Verify email address
if
(! filter_var (
$email
, FILTER_VALIDATE_EMAIL) === false) {
echo
(
"$email is a valid email address"
);
}
else
{
echo
(
"$email is not a valid email address"
);
}
?>
gfg @ example.com is a valid email address
- Clean and validate URL:
In the following example, the filter_var() function first removes all invalid characters from the URL, and then checks if $url is a valid url: Example: -$url
=
" https://www.engineerforengineer.org "
;
// Remove all invalid characters from the URL
$url
= filter_var (
$url
, FILTER_SANITIZE_URL);
// Validate URL
if
(! filter_var (
$url
, FILTER_VALIDATE_URL) === false) {
echo
(
"$url is a valid URL"
);
}
else
{
echo
(
"$url is not a valid URL"
);
}
?>
https://www.engineerforengineer.org is a valid URL
http://php.net/manual/en/function.filter-var.php