使用 txt 文件(包含字符串的大型列表)搜索字谜



我正在创建一个程序来检查看似随机的字母是否实际上是连贯单词的字谜。

我正在使用来自URL的.txt文件,其中包含德语中最常用的单词列表,我将其转换为数组$dictionary其中每个元素都相当于一个单词。

$dictionary = file('https://bwinf.de/fileadmin/user_upload/BwInf/2018/37/1._Runde/Material/woerterliste.txt');

然后,我使用explode()将键入到字段中的字符串转换为数组中的单个单词:

$str = $_POST["str"]; //name of the text field for the string
$words = explode(" ", $str);

然后,我定义函数is_anagram($a, $b)该函数应检查字谜和回显$b,以防它们的字符匹配:

function is_anagram($a, $b) {
if (count_chars($a, 1) == count_chars($b, 1)) {
echo $b . " ";
}
}

为了比较两个数组的元素,我创建了一个foreach循环,在其中使用上述函数:

foreach ($words as $word) {
foreach ($dictionary as $dic) {
is_anagram($word, $dic);
}
}

循环应该回显一些可以在$dictionary中找到的字符串,如果用户编写的字符串具有一些字谜。

但是,当我提交几个我知道是全等字谜的单词时,程序不会回显任何内容。

更奇怪的是,当我使用 .txt 文件将$dictionary定义为一个简单的数组时,例如

$dictionary = ["ahoi", "afer", "afferent"];

该函数按预期工作。

我很确定$dictionary有一些错误,也许是因为.txt文件非常大。有谁知道如何解决这个问题?

$dictionary = file('https://bwinf.de/fileadmin/user_upload/BwInf/2018/37/1._Runde/Material/woerterliste.txt'); 

$dictionary示例中是一个字符串,而不是数组。

$tmpfile = file_get_contents('https://bwinf.de/fileadmin/user_upload/BwInf/2018/37/1._Runde/Material/woerterliste.txt');
$dictionary=explode("n",$tmpfile);

最新更新