vendredi 20 janvier 2017

Get random word of specific length from wordlist

I am writing a simple PHP function that will access word-list.txt and pull a random word (the words are separated by a new line). This word needs to have a maximum length of $maxlength. The way that I have written it, it will pull the word and if the length is too long, then it will keep getting a new word until it is less than or equal to $maxlength. The issue that I am running into is that the script returns a fatal error for a maximum execution time. Here is the code:

function GetWord($maxlength) {
    $file_content = file('word-list.txt');
    $nword = $file_content[array_rand($file_content)];

    while(mb_strlen($nword) > $maxlength) {
        $nword = $file_content[array_rand($file_content)];
    }

    return $nword;
}

The only alternative that I could think of is putting the wordlist into a database and having a column with each corresponding word's length. That would allow me to select the word choices based on their length. I am trying to avoid having to use a database however, so I want to find out what is wrong with my script. Any help is greatly appreciated. Thanks!




Aucun commentaire:

Enregistrer un commentaire