Monday, 2 February 2015

Validate Email By Regular Expression

Validate Email By Regular Expression

Validating an email address by regular expression is not foolproof, even the regular expression in the filter extension is no one hundred percent effective. Some regular expressions are too restrictive and reject valid emails, whilst others allow invalid email addresses through.
Keeping this in mind, this regex will cope with most sane email address that are generally found in normal usage. 

<?php
        
/**
         *
         * @validate an email address by regex
         *
         * @param string $email
         *
         * @return bool
         *
         */
        
function validateEmail($email)
        {
                
$pattern "/^\S+@[\w\d.-]{2,}\.[\w]{2,6}\z/iU";
                return (bool)
preg_match($pattern$email$matches);
        }

    
/*** examle usage ***/
    
$email 'example@phpro.org';

    if( 
validateEmail$email ) == false )
    {
        echo 
'Email is invalid';
    }
    else
    {
        echo 
'Email is valid';
    }
?>

0 comments:

Post a Comment