Reputation: 55
Why code below returns emails ID as false or invalid?
<?php
$okay = preg_match(
'/^[A-z0-9_\-]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z.]{2,4}$/',
"[email protected]"
);
echo $okay;
?>
Upvotes: 1
Views: 65
Reputation: 596
There already is a function from PHP itself to validate emails, I suggest using that instead of a regex.
<?php
$email_a = '[email protected]';
$email_b = 'Random words';
if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_b) email address is considered valid.";
}
?>
More on this can be found here:
http://php.net/manual/en/function.filter-var.php
http://php.net/manual/en/filter.examples.validation.php
Upvotes: 2