PHP - preg_match() and eregi() not working?
I'm having a bit of a problem trying to validate email adresses using preg_match (or eregi() if that suits better). I've tried several regex patterns now and no matter what i do it doesn't seem to work.
Here's the function:
function validateEmail($email) {
if(eregi('[a-z||0-9]@[a-z||0-9].[a-z]', $email)){
return true;
}
}
Any ideas what's wrong? I've tried putting an exclamation point before the eregi (and preg_match that i used before), and that reversed it all (as expected) but still didn't make it work as it should. I want it to return TRUE if it does not pass the regex.
And i didn't use the same reg开发者_如何学编程ex when on the preg_match function, i found another one then, cause i know you can't really mix those two. Right?
Thanks in advance!
You ought to use the filter extension through filter_var
:
filter_var($email, FILTER_VALIDATE_EMAIL);
If you want a regex, don't use a strict rule, or my +@example.org
domain will be rejected. Use something like ~[^@]+@(?:[^.]+\.)+[A-Za-z]{2,6}~
. Though this will still not allow valid emails like "\@"@example.org
.
PS: If you want to know why your regex doesn't work:
- eregi is deprecated, use preg_match instead
- inside
[]
don't write||
. Simply use[a-z0-9]
.||
would simply additionally allow the|
character - You forgot the
+
quantifiers everywhere. Right know every part may have only one character.
With all those things fixed (but please don't use this regex!):
preg_match('~[a-z0-9]+@[a-z0-9]+.[a-z]+~i', $email);
Just to clarify some stuff, ereg
is depreciated.
To convert that to preg_match
it would be:
if(preg_match('/[a-z||0-9]@[a-z||0-9].[a-z]/', $email)){
Most (I use this term loosely) ereg
's just need delimiters (the first and last / ) added to be converted to preg_match
.
精彩评论