如何检查字符串中只有一个“@”字符


How to check that there is only one "@" character in the string?

可能的重复项:
修改正则表达式以验证电子邮件?

$email = $_POST["email"];
if(preg_match("[@{1}]",$email))
    echo "There is only one @ symbol";
if(preg_match("[@{2,}]",$email))
    echo "There is more than one";

这很简单,我的问题,但由于我很少使用正则表达式,因此输出不会以我想要的方式出现。$email的还有帖子数据。

如果$email有 2 个或更多 @ 符号,则将显示有多个符号。如果$email有 1 个@symbol那么它将显示只有 1 个 @ 符号。够容易吧?

你的第一个表达式将在任何地方匹配一个@;它从来没有说它必须是唯一的。

第二个表达式将匹配两个或多个连续@符号。当您有两个被其他东西隔开时,它不会检测到这种情况。

您需要将"只有一个"或"多个"的概念翻译成与正则表达式兼容的术语:

  • "只有一个":一个被非@包围的单个@^[^@]*@[^@]*$

  • "不止一个":两个@用任何内容分隔:@.*@

以及一个相关且有用的概念,即"除了一个之外的任何东西"(即 0、2、3、4...),简单地作为对第一个的否定(即 !preg_match('/^[^@]*@[^@]*$/', $email)

我建议使用这样的explodecount

if (count(explode('@', $email)) > 2) {
    //here you have 2 or more
}

您要实现的目标是什么?您真的想知道其中是否只有一个@还是要验证整个电子邮件地址?如果您想验证它,请查看这篇文章: 修改正则表达式以验证电子邮件?

you need to enclose your regex in delimiters like forward slash(/) or any other char.
$email = $_POST["email"];
if(preg_match("/[@{1}]/",$email))
    echo "There is only one @ symbol"."</br>";
//you have to use preg_match_all to match all chars because preg_match will stop at first occurence of match.
if(preg_match_all("/('w*@)/",$email,$matches)){             //'w matches all alphanumeric chars, * means 0 or more occurence of preceeding char 
    echo "There is more than one"."</br>";
    print_r($matches);}                                 //$matches will be the array of matches found.
?>