php - 使用 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 文件非常大。有谁知道如何解决这一问题?
解决方案
$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);
推荐阅读
- php - file_get_contents - 未找到文件
- arrays - Excel - 在表中查找值以返回第 n 列值
- regex - Hive RegEx Serde 不起作用并加载为 NULL
- firebase - firebase 可以为特定用户提供多少次“currentUser.getIdToken() 和 verifyIdToken()”请求?
- maven - 在詹金斯管道上找不到 mvn 命令
- tensorflow - 运行 tf.Strategy 与 tf.data batch() 时的批处理大小
- angular - 测试 Angular 应用程序时出现 ng2-charts 错误
- webpack - 如何解决 webpack.config.js 条目中的“不允许类型”?
- javascript - Firebase Angular - 按值对我的用户进行排序 - 排序不是函数
- javascript - 创建一个基本的 log() 函数:TypeError:无法将对象转换为原始值