如何解决了解带有数组的foreach
我创建了一个简短的脚本,该脚本应查看$ 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循环中,如果找到了针,就设置一个标志并中断循环。
我正在反转通用顶级域名(TLD)和电子邮件以进行比较,因为这样可以更轻松地比较字符串的结尾。
示例输出针对给定的三个电子邮件输入。
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,.tv"
}
array(0) {
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。