我需要检查一个单词数组($words)是否存在于一个较大的数组($dictionary)中。如果所有的单词都在,就没有错误。如果$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.";
}
?>
此代码总是返回一个错误消息,而不报告找不到哪个单词。最重要的是,实际上缺失的单词不会被检测到。我做错了什么?
显然,问题出在这一行:
$words = preg_replace('/[0-9]+/','',$words);
删除数字会扰乱整个匹配过程。
不删除数字,我的代码工作