php-regexHow to use regex in PHP to validate an email address?
Using regular expressions (regex) in PHP to validate an email address is a common task. The following example code block will check if an email address is valid:
<?php
$email = "[email protected]";
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $email)) {
echo "Valid email address";
} else {
echo "Invalid email address";
}
Output example
Valid email address
The code consists of the following parts:
$email = "[email protected]";
- This is the email address to be validated.preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $email)
- This is the regular expression used to validate the email address. It checks for the presence of an @ symbol, a period, and a valid domain name.echo "Valid email address";
- This is the output if the email address is valid.echo "Invalid email address";
- This is the output if the email address is invalid.
Helpful links
More of Php Regex
- How to use PHP regex to match a nbsp HTML whitespace?
- How to get the first match when using regex in PHP?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match a zip code?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match special characters?
- How to use PHP regex with the "x" modifier?
- How to match a double quote in PHP regex?
- How to use PHP regex to match whitespace?
- How to match a space using PHP regex?
See more codes...