6

I always find regular expressions a headache, and googling didn't really help. I'm currently using the following expression (preg_match): /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/

However, if I'd want to allow emails with plus symbols, this obviously won't work, eg: foo+bar@domain.com

How would I need to change my expression to allow it? Thanks in advance for all the help!

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
Sam Granger
  • 401
  • 5
  • 10
  • You shouldn't use regex to validate email addresses (unles you're willing to compromise) See [this question](http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses) – Madara's Ghost Dec 03 '11 at 17:35

3 Answers3

10

You should just use PHPs builtin regex for email validation, because it covers all the things:

filter_var($email, FILTER_VALIDATE_EMAIL)

See filter_var and FILTER_VALIDATE_EMAIL (or https://github.com/php/php-src/blob/master/ext/filter/logical_filters.c#L499 for the actual beast).

mario
  • 144,265
  • 20
  • 237
  • 291
  • Yeap. That's a nice answer. +1 – FailedDev Dec 03 '11 at 17:38
  • And in case you were wondering, `FILTER_VALIDATE_EMAIL` uses a regex. You can see it on http://svn.php.net/viewvc/php/php-src/trunk/ext/filter/logical_filters.c?view=markup line 525 – Bailey Parker Dec 03 '11 at 18:45
  • Thanks - awesome answer! However, it still doesn't validate foo+bar@domain.com for instance - upgrading my php as we speak so hopefully it's fixed in the latest stable release! – Sam Granger Dec 03 '11 at 21:39
  • 3
    Sorry - it was working, I was getting the email using a $_GET - should of used %2b instead of + in the URI, filter_var is working like a dream!!! – Sam Granger Dec 03 '11 at 22:10
  • @SamGranger: That's super odd. Just tested with PHP 5.2.0 (first version to feature `filter_var`), and it worked for my setup. It might only fail if you have a trailing newline or something. --- Ah, oh well, okay then :] – mario Dec 03 '11 at 22:13
7

Your wrong regex can be changed to another wrong regex:

/^[\w-]+(\.[\w+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/

which allows for the + character where you want it. But it's wrong anyway.

Community
  • 1
  • 1
FailedDev
  • 26,680
  • 9
  • 53
  • 73
1

Try add \+ into the char collection [] :

/^[_a-z0-9-]+(.[_a-z0-9-\+]+)@[a-z0-9-]+(.[a-z0-9-]+)(.[a-z]{2,3})$/
Paulo H.
  • 1,228
  • 10
  • 15