PHP finding out if words are contained in a large array


Keywords:php 


Question: 

I need to check if an array of words ($words) is present in a larger array ($dictionary). If all the words are there, no errors. If one or more are not included in $dictionary, I want to send out an error message. So far, I have come up with this:

<?php
// first I select a column from a MySQL table and retrieve 
//all the words contained in that field.
$spell = "SELECT * FROM eventi WHERE utente='{$_SESSION['username']}'";
$qspell = mysql_query($spell) or die ("Error Query [".$spell."]");
while ($risu = mysql_fetch_array($qspell)){
    $risu = mysql_fetch_array($qspell);
    // the following lines remove parentheses, digits and multiple spaces
    $desc = strtolower($risu["descrizione"]);
    $words = explode(" ",$desc);
    $words = str_replace("(","",$words);
    $words = str_replace(")","",$words);
    $words = preg_replace('/[0-9]+/','',$words);
    $words = preg_replace('/\s+/',' ',$words);
    // the array $dictionary is generated taking a long list
    //of words from a txt file
    $dictionary = file('./docs/dizionario.txt',FILE_IGNORE_NEW_LINES);
    foreach($words as $k => $v){
        if (in_array($v, $dictionary)){
            //Do something?
        } else {
            $error = "error";
            echo "The word ".$v." can't be found in the dictionary.";
        }
    }
}
if (!isset($error)){
    echo "All the words are in the dictionary.";
} else {
    echo "There are some unknown words. See above.";
}
?>

This code always returns one single error message, without reporting which word can't be found. On top of that, words which are actually missing are not detected. What am I doing wrong?


1 Answer: 

Apparently, the problem lies at the line:

$words = preg_replace('/[0-9]+/','',$words);

Removing digits somehow messes the whole matching procedure.

Without removing digits, my code works.