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

时间:2018-10-01 19:52:19

标签: php arrays loops char embed

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

我正在使用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"];

该功能可以正常工作。

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

1 个答案:

答案 0 :(得分:0)

$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);
相关问题