【问题标题】:Find all anagram words in a text file查找文本文件中的所有字谜单词
【发布时间】:2013-12-24 01:45:33
【问题描述】:

所以我有一个单词文件。当一个人输入 a 时,他们应该取回该单词的所有字谜(如果有的话)。

示例:输入 'hat' 使用 h-a-t 检查文件中是否包含 3 个字符

所以这就是我现在的位置..

    $wordlist=file_get_contents('words.txt');
    $word = $_POST['word'];

    $word_split = str_split($word);

    foreach($wordlist as $line){
       if(strpos($line, $word_split) !== false){
          echo $line;
      }
    }

这当然行不通,因为您不能将数组用作指针。所以我被困在如何做到这一点上。

【问题讨论】:

标签: php


【解决方案1】:

如果有任何问题,请在下方评论(我将输入更改为 $_GET 以便于测试)。

//Check first if there's any word input
if(isset($_GET['word'])){
    $wordlist = explode("\n", file_get_contents('words.txt'));
    $word = $_GET['word'];
    $word_split = str_split($word);
    //print_r($word_split);
    $word_length = strlen(trim($word));
    foreach($wordlist as $line){

        $line_split = str_split(rtrim($line));
        $line_length = strlen(trim($line));
        //Check if the lengths are equal
        $diff = array_filter($word_split, function ($val) use (&$line_split) { $key = array_search($val, $line_split);if ( $key === false ) return true;unset($line_split[$key]);return false;});

        if($line_length == $word_length && empty($diff)){
            echo $line."\n";
        }
    }
}else{
    die("No word input.");
}

示例

输入词:post

Word 数据库 (word.txt):

post
some
pots
random
spot
words
stop
for
tops
testing

输出:

post
pots
spot
stop
tops

【讨论】:

  • 谢谢,您的解决方案很接近,但它只是检查单词的长度是否相同,而不是如果我输入 blue dog,它们是否包含相同的字母,我会被打败
  • 还应该做​​什么?
  • 所以如果我在搜索帽子,它应该会找到带有字母 h-a-t 的单词
  • 您说“输入 'hat' 检查文件中是否有任何带有 h-a-t 的 3 个字符”,我正在检查相同的长度和字符。我误会你了吗?
  • 嗯,由于某种原因,当我输入单词时,它没有给我正确的字谜:苹果给了我阿拉拉
猜你喜欢
  • 2015-05-06
  • 2011-12-15
  • 2021-08-27
  • 2019-11-21
  • 2011-02-07
  • 1970-01-01
  • 2013-09-20
  • 1970-01-01
  • 2013-05-28
相关资源
最近更新 更多