搜索数组以进行部分(或精确)匹配

时间:2011-08-08 21:14:57

标签: php arrays match

我有一些代码从txt文件中获取电子邮件列表并将它们插入到数据库中,如果已经在所述数据库中,请确保不添加该电子邮件。我现在要做的是过滤掉从txt文件中读取的电子邮件,如果它们与$ filter数组中的任何字符串完全或部分匹配,则不插入它们。换句话说,如果电子邮件地址中的电子邮件中包含“gmail”,“。ru”或“exec”,我不希望它添加。

任何有助于阻止我将头撞在墙上的帮助都会很棒!

代码:

$TheFile = "emails.txt";

$handle = fopen($TheFile, 'r');

$good_count = 0;
$bad_count = 0;

$filter= array("gmail",".ru","exec");

while (!feof($handle))
{
    $Data = fgets($handle, 1024);
    $output = explode (",",$Data);

    $exist = mysql_query("SELECT * FROM table WHERE email='$output[0]'");

    if (mysql_num_rows ($exist) == 0) {
        $email = strtolower($output[0]);
        $sql = "INSERT INTO table SET email='$email'";
        mysql_query($sql);
        $good_count = $good_count + 1;
    }
    else {
        $bad_count = $bad_count + 1;
    }
}

1 个答案:

答案 0 :(得分:1)

在验证功能中使用stripos

function validate_email($input, array $needles) {
    foreach ($needles as $needle) {
        if (stripos($input, $needle) === false) return false;
    }
    return true;
}

// ...

if (mysql_num_rows ($exist) == 0 &&
    validate_email($output[0], $filter)) 
{
    $email = strtolower($output[0]);
    $sql = "INSERT INTO table SET email='$email'";
    mysql_query($sql);
    $good_count = $good_count + 1;
}
else {
    $bad_count = $bad_count + 1;
}

另外,请考虑在表定义中使用UNIQUE index。如果电子邮件已经存在,这将导致(可捕获的)MySQL错误,并且会卸载您的脚本,对文件中的每封电子邮件执行SELECT查询。