-4

I'm learning PHP regular expressions, and I came across something I'm having trouble making sense of.

The book gives this example in validating an e-mail address.

if (ereg("^[^@]+@([a-z0-9\-]+\.)+[a-z]{2,4}$", $email))

I'm not clear on a couple elements of this expression.

  1. what does this mean [^@]+@
  2. What is the purpose of the parentheses in ([a-z0-9\-]+\.)?
Whisperity
  • 2,904
  • 1
  • 15
  • 35
Hermes
  • 1
  • Try this tutorial: http://www.regular-expressions.info/tutorial.html/ – Ed Manet Aug 06 '12 at 19:47
  • don't use ereg, its depreciated, i would say you book is dated. Don't use regular expressions for validating email addresses; use filters –  Aug 06 '12 at 19:54

1 Answers1

6

[^@]+@ means:

[   - Match this group of characters
 ^@ - Anything that is NOT an at sign
]
+   - One or more times
@   - Match an at sign

So, it's essentially matching every character before the first at sign.

The purpose of parenthesis in ([a-z0-9-]+.) is to create a capturing group, which you should be able to reference later on once the group captures some amount of text.

Also note that ereg_* functions are deprecated, and your book must be a bit dated. Nowadays, we use the preg_* family of functions. A tutorial on converting them can be found in this SO question.

Community
  • 1
  • 1
nickb
  • 56,839
  • 11
  • 91
  • 130
  • 2
    fyi that's not an [ampersand](http://en.wikipedia.org/wiki/Ampersand), it's an [at sign](http://en.wikipedia.org/wiki/At_sign). – Gordon Bailey Aug 06 '12 at 19:49
  • @Gordon - Hah, you are correct good sir. Thanks for pointing that out, I've fixed it. – nickb Aug 06 '12 at 19:50
  • Thanks, and yeah I noticed the tutorials are written in POSIX syntax, which brings up deprecated errors like you said. I use PCRE which is more up to date. – Hermes Aug 06 '12 at 20:01