Sep
17
PHP Regex - Validate Email Address
September 17, 2008 |
This article is for our friend Josh and all those who might be interested in knowing how to validate email address using PHP Regex (Regular Expression). The script below makes sure an e-mail address looks like a valid address, containing a username, @, and valid hostname. For example, null@example.com is valid, but NOSPAM@spam isn’t valid.
<html>
<head><title>4-11 Validating e-mail addresses</title></head>
<style>
.err { color : red ; font-weight : bold }
</style>
<body>
<form action="recipe4-11.php" method="post">
<input type="text" name="input" /><br/>
<input type="submit" value="Submit Form" /><br/><br/>
<?php
if ( $_SERVER['REQUEST_METHOD'] == "POST" )
{
$input = $_POST['input'];
if ( preg_match( "/^[-\w.]+@([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}$/", $input ) )
{
# Do some processing here - input if valid
}
else
{
print "<span class=\"err\">Bad e-mail address. Please correct ".
"and resubmit the form</span><br/>";
}
}
?>
</form>
</body>
</html>
Regular Expression Explanation:
|
( |
a group that includes … |
|
[A-z0-9] |
a letter or number … |
|
[-A-z0-9] |
a letter, number, or hyphen … |
|
\. |
a literal dot or period … |
|
) |
the end of the group … |
|
+ |
found one or more times … |
|
[A-z] |
a letter … |
|
{2,4} |
found between two and four times. |
Similar Posts
- PHP Regex Extract Username from Email Address
- PHP Regex Validate IP address
- Validate URL Using PHP Regex
- PHP Regex Extract Directiory from Full Path
- PHP Regex - Extract Filenames from Full Path
- PHP Regex Extract Filename from Full Path
- PHP Regex Remove Whitespace from HTML
Comments
4 Comments so far



































Hi, thanks for sharing this script, the explanation about how PHP Regex work is very clear.
Hi, I agree with zeriano. PHP POSIX Regular Expression looks like gibberish to me, but with your code explanation, it’s very easy to understand.
Like most of your articles, clear, easy to read and comprehensive. :) keep it up!
Love your script, hope to see more useful script from your site!