PHP filter_var() Function
Example
Check if $email is a valid email address:
<?php
$email = "john.doe@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>
Try it Yourself »
Definition and Usage
The filter_var() function filters a variable with the specified filter.
Syntax
filter_var(var, filtername, options)
Parameter Values
Parameter | Description |
---|---|
var | Required. The variable to filter |
filtername | Optional. Specifies the ID or name of the filter to use. Default is FILTER_DEFAULT, which results in no filtering |
options | Optional. Specifies one or more flags/options to use. Check each filter for possible options and flags |
Technical Details
Return Value: | Returns the filtered data on success, FALSE on failure |
---|---|
PHP Version: | 5.2+ |
More Examples
The example below both sanitizes and validates an email address:
Example
First remove illegal characters from $email, then check if it is a valid email address:
<?php
$email = "john.doe@example.com";
// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate e-mail
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>
Try it Yourself »
❮ PHP Filter Reference
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.