Skip to content

Instantly share code, notes, and snippets.



Last active Aug 30, 2019
What would you like to do?
PHP: Email Validation (RFC 2822)
* Verifies the syntax of the given e-mail address.
* See RFC 2822 for details.
* @param $mail
* A string containing an e-mail address.
* @return
* 1 if the email address is valid, 0 if it is invalid or empty, and FALSE if
* there is an input error (such as passing in an array instead of a string).
function valid_email_address($mail)
$user = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+';
$domain = '(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+';
$ipv4 = '[0-9]{1,3}(\.[0-9]{1,3}){3}';
$ipv6 = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}';
return preg_match("/^$user@($domain|(\[($ipv4|$ipv6)\]))$/", $mail);

This comment has been minimized.

Copy link

@Verron Verron commented Sep 2, 2015

Very useful. Have you considered contributing to get PHP's filter_var to follow RFC 2822 and not RFC 822?


This comment has been minimized.

Copy link

@matudelatower matudelatower commented Aug 3, 2017

how to void dot in


This comment has been minimized.

Copy link

@p4prawin p4prawin commented Jun 25, 2018

Above function could not validate emails like John Smith which is a standard format of RFC 2822
I have created a function which will validate both.

function validate_email($email) {
  $email_matches = array();

  $from_regex   = '[a-zA-Z0-9_,\s\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+';
  $user_regex   = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+';
  $domain_regex = '(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+';
  $ipv4_regex   = '[0-9]{1,3}(\.[0-9]{1,3}){3}';
  $ipv6_regex   = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}';

  preg_match("/^$from_regex\s\<(($user_regex)@($domain_regex|(\[($ipv4_regex|$ipv6_regex)\])))\>$/", $email, $matches_2822);
  preg_match("/^($user_regex)@($domain_regex|(\[($ipv4_regex|$ipv6_regex)\]))$/", $email, $matches_normal);

  // Check for valid email as per RFC 2822 spec.
  if (empty($matches_normal) && !empty($matches_2822) && !empty($matches_2822[3])) {
    $email_matches['from_name'] = $matches_2822[0];
    $email_matches['full_email'] = $matches_2822[1];
    $email_matches['email_name'] = $matches_2822[2];
    $email_matches['domain'] = $matches_2822[3];

  // Check for valid email as per RFC 822 spec.
  if (empty($matches_2822) && !empty($matches_normal) && !empty($matches_normal[2])) {
    $email_matches['from_name'] = '';
    $email_matches['full_email'] = $matches_normal[0];
    $email_matches['email_name'] = $matches_normal[1];
    $email_matches['domain'] = $matches_normal[2];

  return $email_matches;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.