繁体   English   中英

用数组理解 foreach

[英]Understanding foreach with arrays

我创建了一个简短的脚本,它应该查看 $email 并查看是否有 @ 符号并告诉您是否有。 然后,它应该检查每个扩展名 $protocols 数组并告诉您 $email 中是否有扩展名。 它通过 $protocols 的前两个; 然而,在没有错误消息的情况下停止冷态或继续执行 $protocols。

<?
// Set searching info!
    $attsymbol = "@";
    $protocols = array('.com', '.net', '.org', '.biz', '.info', '.edu', '.mil', '.cc', '.co', '.website', '.site', '.tech', '.tv');

// Set email
    $email = "bob@email.website";

// check for the @ symbol!
    if (!strpos($email, $attsymbol))
        {
            die ("There is no " . $attsymbol . " in the email address!<br>");
        }
    else
        {
            echo "This is an " . $attsymbol . " in the email address!<br>";
// Check for all of the protocols in the array!

    foreach ($protocols as $protocol)
        {
        echo $protocol . "<br>";
            if (!strpos($email, $protocol))
                {
                    die("There is no " . $protocol . " in the email address!<br>");
                }
            else
                {
                    echo"There is a " . $protocol . " in the email address!<br>";
                }

        }
    }

?>

在此先感谢您的帮助!

相反,您可以使用FILTER_VALIDATE_EMAIL来检查该值是否为有效的电子邮件地址。

<?php

$email = "bob@email.website";

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "<pre>Valid</pre>";
} else {
    echo "<pre>Not Valid</pre>";
}

你想循环并寻找你的针。

在接下来的 I 循环中,如果我找到针,我设置一个标志并打破循环。

我正在反转 tlds 和电子邮件以进行比较,因为比较字符串的结尾更容易。

示例输出针对三个给定的电子邮件输入。

foreach(['jimbob', 'bob@example.uk', 'bob@email.website'] as $email) {
    $errors = [];
    $tlds   = ['.com', '.net', '.org', '.biz', '.info', '.edu', '.mil', '.cc', '.co', '.website', '.site', '.tech', '.tv'];

    // @ check.
    if (strpos($email, '@') === false) {
        $errors[] = 'No @ in address.';
    }

    // tld check.
    $reversed_tlds  = array_map('strrev', $tlds);
    $reversed_email = strrev($email);
    $found = false;
    foreach($reversed_tlds as $reverse_tld) {
        if(strpos($reversed_email, $reverse_tld) === 0) {
            $found = true;
            break;
        }
    }
    if(!$found) {
        $errors[] = 'Email address must end in one of: ' . implode(',', $tlds);
    }

    var_dump($errors);
}

输出:

array(2) {
  [0]=>
  string(16) "No @ in address."
  [1]=>
  string(102) "Email address must end in one of: .com,.net,.org,.biz,.info,.edu,.mil,.cc,.co,.website,.site,.tech,.tv"
}
array(1) {
  [0]=>
  string(102) "Email address must end in one of: .com,.net,.org,.biz,.info,.edu,.mil,.cc,.co,.website,.site,.tech,.tv"
}
array(0) {
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM