PHP从文件中读取行并比较它们


PHP reading lines from file and compare them

我正在尝试从文件中读取所有行,然后查看给定字符串是否包含这些行。

我的代码
$mails = file('blacklist.txt');
$email = "hendrik@anonbox.net";
$fail = false;
foreach($mails as $mail) {
    if(strpos($email, $mail) > 0) {
        $fail = true;
    }
}
if($fail) {
    echo "Fail";
} else {
    echo "you can use that";
}

blacklist.txt可以在这里找到http://pastebin.com/aJyVkcNx。

我希望strpos返回黑名单中至少一个字符串的位置,但它没有。我猜,不知何故,我在$mails内生成的值不是我所期望的那种。

编辑这是print_r($mails) http://pastebin.com/83ZqVwHx

EDIT2一些澄清:我想看看一个域名是否在电子邮件中,即使邮件包含subdomain.domain.tld。我试图使用!== false而不是我的> 0,产生了相同的结果。

您需要很好地解析电子邮件,因为您正在检查电子邮件地址的域,如果它在黑名单内。例子:

$email = "hendrik@foo.anonbox.net";
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
    preg_match('/@.*?([^.]+[.]'w{3}|[^.])$/', $email, $matches);
    if(!empty($matches) && isset($matches[1])) {
        $domain = $matches[1];
    } else {
        // not good email
        exit;
    }
    // THIS IS FOR SAMPLES SAKE, i know youre using file()
    $blacklist = explode("'n", file_get_contents('http://pastebin.com/raw.php?i=aJyVkcNx'));
    foreach($blacklist as $email) {
        if(stripos($email, $domain) !== false) {
            echo 'you are blacklisted';
            exit;
        }
    }
}
// his/her email is ok continue

strpos如果未找到字符串则返回FALSE。'

简单地使用:

$fail = false;
foreach($mails as $mail) {
    if(strpos($email, $mail) === false) {
        $fail = true;
    }
}

或者用这个更好:

$blacklist = file_get_contents('blacklist.txt');
$email = "hendrik@anonbox.net";
if(strpos($email, $blacklist) === false){
    echo "fail";
} else {
    echo "This email is not blacklisted";
}

您已经发现了strpos函数的常见缺陷。strpos函数的返回值指的是它找到字符串的位置。在这个实例中,如果字符串从第一个字符开始,它将返回0。注意0 !== false

使用这个函数的正确方法是:

if(strpos($email, $mail) !== false){
    // the string was found, potentially at position 0
}

然而,这个函数可能根本不需要;如果您只是检查$mail是否与$email相同,而不是查看字符串是否存在于更大的字符串中,则只需使用:

if($mail == $email){
    // they are the same
}

虽然您可能仍然使用foreach,但这是array reduce模式:

function check_against($carry, $mail, $blacklisted) { 
  return $carry ||= strpos($mail, $blacklisted) !== false;
};
var_dump(array_reduce($mails, "check_against", $email_to_check));

希望能有所帮助。

这是另一种解决方法。

$blacklist = file_get_contents('blacklist.txt');
$email = "hendrik@x.ip6.li";
$domain = substr(trim($email), strpos($email, '@')+1);
if(strpos($blacklist, $domain)){
    echo "Your email has been blacklisted!";
}else{
    echo "You are all good to go! not blacklisted :-)";
}

古德勒克!