开发者

Searching array for partial (or exact) match [duplicate]

This question already has answers here: Filter multidimensional array based on partial match of search value (3 answers) Closed 1 year ago.

I have some code that takes from a txt file a list of emails and inserts them into a database, making sure not to add the email if it's already in said database. What I'm trying to do now is filter emails as they are read from the txt file and NOT insert them if they are an exact or partial match to any strings with开发者_StackOverflowin the $filter array. In other words, if the email has 'gmail', '.ru' or 'exec' anywhere within the email address, I don't want it added.

Any help to stop the bleeding from me pounding my head against a wall would be great!

The code:

$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;
    }
}


Use stripos in a validation function:

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;
}

Also, consider using a UNIQUE index in your table definition. This will cause a (catchable) MySQL error if the email already exists and will offload your script from doing a SELECT query for every email in your file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜