如何从表单 post 检查电子邮件地址中的 @

How to check for an @ in an email address from a form post

我有一个登录和注册表格。

我的表格

<form method="POST" action="login.php">
    <input type="text" name="mail" value="Input your email"/>
    <input type="submit" value="Check"/>
</form>

如果有人输入他们的电子邮件,我想检查地址中是否有 @。我试过使用数组,但它不起作用。

可以使用php函数strposhttp://php.net/strpos

if(strpos($myEmailPostVariable, '@') === FALSE) {
    // do things here to say it failed
}

如果您固定使用数组,那么您可以使用 explode http://php.net/explode

$parts = explode('@', $myEmailPostVariable);
if(count($parts) != 2) {
    // do things here to say it failed
}

请记住,数组方式不是很好,因为搜索字符串更容易、更快速并且更具可读性。

正如@jeroen 所建议的那样,如果您想验证电子邮件,那么使用 filter_input() 是最好的...

if(filter_input(INPUT_POST, 'mail', FILTER_VALIDATE_EMAIL) === FALSE) {
    // do things here to say it failed
}