2

So I have a file of words. When a person enters a they should get back all anagrams of that word if any.

Example: enter 'hat' check the file for anything 3 characters with h-a-t

so this where I am at now..

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

This of course is not working because you cannot use an array as the needle. So I am stuck on how to do it.

Andy
  • 111
  • 1
  • 12

1 Answers1

0

Comment below if there's anything wrong with it (I changed the input to $_GET for easier testing).

//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.");
}

Example

Input word: post

Word database (word.txt):

post
some
pots
random
spot
words
stop
for
tops
testing

Output:

post
pots
spot
stop
tops