PHP查找单词是否包含在大型数组中

时间:2016-10-24 18:41:31

标签: php arrays words

我需要检查一个更大的数组($ dictionary)中是否存在单词数组($ words)。 如果所有单词都存在,则没有错误。 如果$ dictionary中没有包含一个或多个,我想发送一条错误消息。 到目前为止,我已经想出了这个:

<?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.";
}
?>

此代码始终返回一条错误消息,而不报告找不到哪个字。 最重要的是,未检测到实际缺失的单词。 我做错了什么?

1 个答案:

答案 0 :(得分:0)

显然,问题在于:

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

删除数字会以某种方式混淆整个匹配过程。

不删除数字,我的代码可以正常工作。

相关问题