Welcome to Server Circle. It's a friendly site and all levels of experience are welcome. Be aware that we use cookies for your login.
Server Circle - Ask questions about Servers and get answers from experts.
Beta (0.27 sec)
Regex for valid email address in PHP function

This is failing for some reason - all I want is working regex for a valid email address in any PHP function that works !

if (preg_match('/^([a-z0-9_-]+)(\.[a-z0-9_-]+)*@([-a-z0-9]+\.?)+\.[a-z]{2,4}$/i', $email)) {

execute ...

}

Mmm. Any ideas ? Thanks.
Asked by:
twosongs
920 points
 Report Abuse
 Share Page - Category: Programming - Tags: Regex for valid email address in PHP function
 Enter your response
Please use Pastie.org to paste lengthy code or to fix formatting issues with code
  • Responses in reverse (2)

Best Answer


Response by:
s
3383 points
Rather than trying to validate them manually which is really really hard to get working on every email address going, why not use one of the inbuilt filter functions, eg:

$email = "this@example.com";

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {

echo "This (email_a) email address is considered valid.";

}



The trouble with email addresses is there are so many variations allowed under the RFC's including lots of character that you might not think of as legit such as "+" that any validation script almost always breaks.

This example and such comes from:

http://uk2.php.net/manual/en/book.filter.php

...although you need PHP 5.2.x and I only found out about them by accident about a month ago.

Response by:
trevHCS
640 points


  • Related Questions
About Us : Contact Us : Etiquette : Terms : CDN Failover : ShorterURL : CDN Fallback : © 2013 Server Circle