0

I'm trying to validate an email address using preg_match..

But i'm getting this error..

Warning: preg_match(): Unknown modifier '+'

This is my code

preg_match("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", $email, $matches);

Can someone tell me what is wrong with my regex?

Thanks

3
  • 1
    I'd strongly recommend not writing this code yourself. code.google.com/p/php-email-address-validation/source/browse/… Commented May 11, 2013 at 14:26
  • 1
    even space is a valid char in email..point is don't use regex to parse email..put it as simple as this .*@.* that's it Commented May 11, 2013 at 14:26
  • You can be more restrictive on the right side of the @, which has to be a valid domain name, but yeah, pretty much anything goes on the left. Commented May 11, 2013 at 14:37

1 Answer 1

2

You need to put delimiters around the regex when you use preg_match. The standard is /. If you use the delimiter in the expression, you have to escape it.

preg_match("/[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/", $email, $matches);

You could also consider using

filter_var($email, FILTER_VALIDATE_EMAIL);
Sign up to request clarification or add additional context in comments.

3 Comments

Also, these expressions (?:[a-z0-9-]*[a-z0-9])? are a little odd. Presumably they could be replaced with [a-z0-9-]*? for simplicity.
@BoristheSpider I would think that it should be [a-z0-9-]+? :)
@HamZaDzCyberDeV I don't think so, as + requires at least one wheres the construction in a non capturing group followed by a ? which means that it is optional (required zero or one time) - so the expression is saying [a-z0-9-] zero or more times (i.e. a *). On second thoughts i'm not even sure the ? is required - the expression can be greedy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.