Use PHP to detect if given string is a proper email address


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function is_proper_email($email) {
  2. // First, we check that there's one @ symbol, and that the lengths are right
  3. if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
  4. // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
  5. return false;
  6. }
  7. // Split it into sections to make life easier
  8. $email_array = explode("@", $email);
  9. $local_array = explode(".", $email_array[0]);
  10. for ($i = 0; $i < sizeof($local_array); $i++) {
  11. if (!ereg("^(([A-Za-z0-9!#$%&#038;'*+/=?^_`{|}~-][A-Za-z0-9!#$%&#038;'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
  12. return false;
  13. }
  14. }
  15. if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
  16. $domain_array = explode(".", $email_array[1]);
  17. if (sizeof($domain_array) < 2) {
  18. return false; // Not enough parts to domain
  19. }
  20. for ($i = 0; $i < sizeof($domain_array); $i++) {
  21. if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
  22. return false;
  23. }
  24. }
  25. }
  26. return true;
  27. }
  28.  
  29. //usage
  30. // $email_result = is_proper_email($email_string);
  31. // $email_result will be either true or false

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.