Select random strings of more than 6 and less than 10 characters from a text file

I have a text file and I need to select a random line that contains more than 6 characters and no more than 10 characters. Normally I would use a script like this one that will work, but since it must be of a certain length, this will not work. Anyone have a solution?

An example input would be something like this:

Apple
Banana
Orange
Strawberry
Blueberry
Pineapple
Somelongfruithere

These values ​​will be in the .txt file, each with a line break. An example of a string to be resolved is pineapple, but appleor Somelongfruitherewill not be resolved.

+3
source share
5 answers

You will need to do something like this:

$lines = array();
$tmpLines = file('random.txt');
for($i = 0; $i < count($tmpLines); ++$i)
{
    if(strlen($tmpLines[ $i ]) > 6 && strlen($tmpLines[ $i ]) < 10)
    {
        $lines[] = $tmpLines[ $i ];
    }
}
$randomWord = $lines[ array_rand($lines) ];

( ):

$randomWord = '';
$lines = file('random.txt');
while(strlen($randomWord) <= 6 || strlen($randomWord) >= 10)
    $randomWord = $lines[ array_rand($lines) ];

, 6 10 . "" .

, , . , . , .

+1

explode , , ( ), ( do/while), , , ,

if (strlen($rand_word) > 6 && strlen($rand_word) < 10) {
   //execute function and end loop 
} else {
// keep checking using a new random placement number
}
+1

. , , strlen , .

strlen, , 6 , substr, 10. , ltrim rtrim strlen substr.

+1

, , :

$fileLines = file('somefile.txt');
$myWords = array();
foreach ($fileLines as $line)
{
    $thisLine = split(" ",$line);
    foreach ($thisLine as $word)
    {
        $length = strlen($word);
        if ($length > 6 && $length < 10)
        {
            $myWords[] = $word;
        }
    }
}

$randomWord = $myWords[array_rand($myWords)];
0

!

for ($i=7; $i<=9; $i++)
    if (strlen($str) == $i )
       echo "bingo! " . strlen($str);
-1

All Articles