Verify and e-mail address format
There are several ways to determine if a variable contains a valid email address. These techniques do not check if email address exists, but they determine if the string contained in a variable complies with the format of an email address.
Using a filter
Using a function of the family of filters, you can check that email address is valid.
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
//e-mail is good
}
With regular expressions
It is possible to check if an email address, for example via entry form, is valid.
Here is a function that checks if a string is only a valid e-mail address.
function Verifyemailaddress($address)
{
$Syntax='#^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$#';
if(preg_match($Syntax,$address))
return true;
else
return false;
}
Example of use
After getting the "address" field of a form:
$address=htmlentities($_POST['address']);
if(Verifyemailaddress($address))
echo '<p>Your address is valid.</p>';
else
echo '<p>Your address is not valid.</p>';
Explanations
The sharps are the regex delimiters.
The symbol ^ indicates that the string must begin with what follows, and the $ sign indicates that it must end with the above.
\ w is a class which is abbreviated to A-Za-z0-9_. either the 26 letters of the alphabet in upper or lower case, the ten digits and underscore.
What does the code do
^ [\ w. -] + @ Begins (^) by at least one character corresponding to the abbreviated class, or a dash, then followed by an @.
[\ w. -] + one or more characters corresponding to the abbreviated class or a dash (the domain name)
\. [a-zA-Z] (2.6) $ a, then two to six letters, that eventually the chain (the tld of the domain name).