9951 explained code solutions for 126 technologies


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:

  1. $email = "[email protected]"; - This is the email address to be validated.
  2. 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.
  3. echo "Valid email address"; - This is the output if the email address is valid.
  4. echo "Invalid email address"; - This is the output if the email address is invalid.

Helpful links

Edit this code on GitHub