Speed up development with full-stack environments for every branch.

Learn More

How to check if a email address is valid using regular expressions [PHP and PCRE]

1946 Runs 21015 Views 14103 Copies
Saved

Saved

gtsolutions 373

gtsolutions
published 4 years ago

<?php
/*
 * PHP PCRE - How to check if a email address is valid using regular expressions
 */

//A valid email address
$email = "[email protected]";
//the pattern is "any letter or number followed by @ followed by any letter or number 
//followed by . followed by 2-4 letters and maybe another . (for tlds like co.uk)
$okay = preg_match(
        '/^[A-z0-9_\-]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z.]{2,4}$/', $email
);
if ($okay) {
    echo $email." is valid<br />";
} else {
    echo $email." is invalid<br />";
}

//An invalid email address
$email = "email[at]example[dot]com";
//the pattern is "any letter or number followed by @ followed by any letter or number 
//followed by . followed by 2-4 letters and maybe another . (for tlds like co.uk)
$okay = preg_match(
        '/^[A-z0-9_\-]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{2,4}$/', $email
);
if ($okay) {
    echo $email." is valid<br />";
} else {
    echo $email." is invalid<br />";
}
?>
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).