سؤال

I am using the following FUNCTION to extract email address from text.

function is_valid_email($email) {
    if (preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.([a-z]){2,4})$/',$emailss)) return true;
    else return false;
}

It is working very smoothly, but on problem: an email with "dash" is not working:

for example:

info-test@web-site.com comes out: test@web

Please advise.

هل كانت مفيدة؟

المحلول

Dash has special meaning in regular expression. So cant be used directly and need to be escaped using backslash. following is updated code:

function is_valid_email($email) {
    if (preg_match('/^[_a-z0-9\-]+(\.[_a-z0-9\-]+)*@[a-z0-9\-]+(\.[a-z0-9\-]+)*(\.([a-z]){2,4})$/',$emailss)) return true;
    else return false;
}

نصائح أخرى

You should escape the dash character, as it has a special meaning (range) in the used context:

[_a-z0-9\-]

There are myriads of problems with that e-mail validation regexp. For example, it won't pass any of perfectly valid modern national TLDs and it honestly thinks that TLD has maximum 4 letters in it. It doesn't allow arbitrary number of dots . in user account part, it doesn't allow pluses +, etc.

Generally, a good practice of validating e-mails boils down to:

  1. Minimal validation - just check that there's @ there and that's all.
  2. Just send that e-mail - don't check anything else. If it will be sent - then it's indeed a valid e-mail.

For more details, take a look at http://davidcel.is/blog/2012/09/06/stop-validating-email-addresses-with-regex/ or any similar articles.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top