Forum Moderators: coopster
e.g.
$string="test@example.com"; --> pass
$string="foo@example.com"; --> pass
$string=""; --> pass
Of course:
$string="testexample.com"; --> fail
$string="@example.com"; --> fail
$string=" "; --> fail
Can anyone help me?
function email($email) { [1][edited by: dreamcatcher at 1:20 pm (utc) on July 19, 2007]
// <snip>
// First, we check that there's one @ symbol, and that the lengths are right
if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("@", $email);
if(sizeof($email_array) > 2){
return false;
}
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{¦}~-][A-Za-z0-9!#$%&'*+/=?^_`{¦}~\.-]{0,63})¦(\"[^(\\¦\")]{0,62}\"))$", $local_array[$i])) {
return false;
}
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array)) { // Check if domain is IP. If not, it should be valid domain name
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])¦([A-Za-z0-9]+))$", $domain_array[$i])) {
return false;
}
}
}
unset($email_array);
unset($local_array);
return true;
}
[edit reason] no urls as per T.O.S [webmasterworld.com].Thanks [/edit]
or I do not read you well :)
Pharion is that () taking care of empty str? I might (am not regex expert) be wrong, but it does not look like it considers "empty str" as ok.
...however, due to programming constraints, I need to do this using a single REGEX in a single preg_match()...
The requirement is that it is either EMPTY or a Valid Email Address. I'm not too fussy about the precise validation of the email address - just a general one for something which could be valid is good enough for me.
Hopefully some kind of alternation of pattern will work? Any ideas?
You could also write your own function (or use one that already exists [webmasterworld.com]) and modify it to check for the empty string OR the regular expression and return TRUE or FALSE accordingly.
// handle empty string in the function itself
if (isValidInetAddress($email)) {
...
}
... or you could do ...
// handle empty string here
if (!$email ¦¦ isValidInetAddress($email)) {
...
}
[edited by: coopster at 1:59 pm (utc) on July 20, 2007]
[edit reason] removed link [/edit]
You can likley accomplish your goal in the same regex if you use an alternative pattern (vertical bar)
That's what I think I'm looking for, but I can't get that to work properly. Can someone give me an example of using the alternation to choose between 'exactly nothing' and 'some other pattern'?
chuckstarks - thanks for that function, however I need to do it with one single regular expression