2014-10-04 132 views
2

我目前正试图弄清楚如何检查并查看$ _POST ['email']是否包含使用php的特定字符串。

我目前试图

}elseif(empty($_POST['email']) || !strpos('@gmail.com', $_POST['email'])) { 

输出表示,对strpos不包含的结局,当它。我现在做错了什么,还是有另一种方法呢?

我只希望人们能够使用gmail进行注册,而不是其他任何未知的电子邮件帐户用于垃圾邮件使用。

+0

你应该使用'strpos(..)=== FALSE'代替'!strpos(..)',因为它也可以返回0作为索引。 – mithunsatheesh 2014-10-04 04:03:56

+0

[Get all $ \ _ POST变量以特定文本开头](http://stackoverflow.com/questions/8825001/get-all-post-variables-starting-with-certain-text)可能重复。 – jww 2014-10-04 04:14:09

+0

@ md_5检查我在下面发布的内容。你最好使用'preg_match()'来做这件事。 – 2014-10-04 15:39:02

回答

1

你可能最好关闭使用preg_match\b模式匹配,而不是strpos。另外,strpos将匹配GMAIL如果您不需要大写字母,则您希望使用stripos,而不是将其与匹配作为区分大小写,FYI

使用strpos将匹配gmail.comm而不是预期gmail.com,我相信你不想要。用户可以很好地输入[email protected]并且仍然被认为是有效的,我确信你不想要的其他东西,在尝试回复邮件或使用自动回复器时会失败。

“的模式中的\ b表示一个字边界,因此只有不同 *单词 “web” 匹配时,和不偏像“带子”或“蜘蛛网”一词

这将不匹配@ 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'])) 

+1

国际海事组织,这是好得多,无论如何,我希望当OP回到网上,应该考虑选择这一个。 – Ghost 2014-10-05 00:42:08

+0

@鬼魂感谢幽灵。 :) – 2014-10-05 01:03:57

+0

感谢@Fred -ii-今天的帮助,以及我今天想出我的错误和困惑。使用preg_match,因为你做了更多更精确的方法来做到这一点,为我今后可能发生的事情节省了很多麻烦。 – 2014-10-05 05:16:18

1

如果您想尝试,而不是strpos别的东西,你可以这样做:

if (empty($_POST['email'] || array_pop(explode('@', $email)) != "gmail.com") { 
    // Do something if the email is empty or the domain is not "gmail.com" 
} 
相关问题