我目前正在尝试弄清楚如何使用 php 检查 $_POST['email'] 是否包含特定字符串。
我目前尝试过
}elseif(empty($_POST['email']) || !strpos('@gmail.com', $_POST['email'])) {
输出表明 strpos 不包含结尾,而实际上它包含结尾。我目前做错了什么,或者还有其他方法吗?
我只希望人们能够注册 Gmail,而不是任何其他用于垃圾邮件的未知电子邮件帐户。
最佳答案
您可能最好使用 preg_match
与 \b
模式匹配而不是 strpos
。另外,strpos
将匹配GMAIL
如果您不需要大写字母,则可以使用 stripos
相反,这会将其匹配为不区分大小写,供引用。
使用strpos
将匹配gmail.comm
而不是预期的 gmail.com
,我确信你不想要这样。用户可以很好地输入<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81e4ece0e8edc1e6ece0e8edafe2eeecec" rel="noreferrer noopener nofollow">[email protected]</a>
并且仍然被认为是有效的,我确定您不想要其他东西,这在尝试回邮或使用自动回复时都会失败。
- 摘自手册http://php.net/manual/en/function.preg-match.php - 基于示例#2
"The \b in the pattern indicates a word boundary, so only the distinct * word "web" is matched, and not a word partial like "webbing" or "cobweb"
这不会匹配@GMAIL.com或@GMAIL.comm,但会匹配@gmail.com,但不@gmail.comm
<?php
if(isset($_POST['submit'])) {
$contains = "@gmail.com";
$email = $_POST['email'];
// or use (as outlined below)
// if(isset($_POST['email']) && preg_match("/\b(@gmail.com)\b/", $_POST['email']))
if(isset($_POST['email']) && preg_match("/\b($contains)\b/",$email )) {
echo 'yey! gmail!';
} else {
echo 'invalid input!';
}
}
?>
<form method="POST">
<input type="text" name="email" />
<input type="submit" name="submit" />
</form>
您还可以执行以下操作,替换您当前使用的内容:
if(isset($_POST['email']) && preg_match("/\b(@gmail.com)\b/", $_POST['email']))
关于php - 检查 $_POST 是否包含特定字符串 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26189462/