首页 > 解决方案 > 使用 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如果用户编写的字符串具有一些字谜,则循环应该回显可以在 中找到的一些字符串。

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

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

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

该功能按预期工作。

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

标签: phparraysloopscharembed

解决方案


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

推荐阅读