Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save p4prawin/4f183fecc611e301cea7875716528ce6 to your computer and use it in GitHub Desktop.
Save p4prawin/4f183fecc611e301cea7875716528ce6 to your computer and use it in GitHub Desktop.
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