我做了一个小的PHP脚本来检查电子邮件是否有效。唯一的问题是它不检查点是否在"@"后面。它接受这样的电子邮件:Hi.Hello@hotmailcom什么时候它应该只接受像 HiHello@hotmail.com 这样的电子邮件
这是我的脚本:
<?php
$mail = $_POST['mail'];
function checkmail($mail)
{
if ((strpos ($mail, '@') !== false) && (strpos ($mail, ".") !==false))
{
return true;
}
else
{
return false;
}
}
if(checkmail($mail))
{
echo"Goed";
}
else
{
echo"Fout";
}
?>
提前感谢!
不要严重地重新发明轮子,使用filter_var('bob@example.com', FILTER_VALIDATE_EMAIL)
,或者在你的情况下更好的filter_input(INPUT_POST, 'mail',
FILTER_VALIDATE_EMAIL)
。
http://php.net/filter_varhttp://php.net/filter_input
如上文所述,您可以使用filter_var
PHP函数,但前提是您的PHP版本高于5.2.0。如果您想要一些更通用的电子邮件验证,您还可以使用正则表达式,有关详细信息,请参阅此处和此处。
if (
(strpos ($mail, '@') !== false) &&
(strpos ($mail, '@') == strrchr($mail, '@')) &&
(strripos($mail, ".") > strpos ($mail, '@'))
)
{return true;}
// explication:
//
// (strpos ($mail, '@') !== false) => '@' character is in the string
// (strpos ($mail, '@') == strrchr($mail, '@')) => '@' character is unique
// (strripos($mail, ".") > strpos ($mail, '@')) => last position of '.' character is
// greater than '@' character position