I have file which contain one very long line string with only letters. No spaces, no new lines.
Currently I'm trying to create function which take two parameters - how many chars and how many words and creates random words.
Example 3 chars, 4 words - asd
, jhH
, OPa
, BaK
.
This is my current function
function randomStringWords($words = 0, $chars = 0) {
$fileRead = fopen("myFile.txt", "r");
if ($fileRead) {
while (($line = fgets($fileRead)) !== false) {
$charactersLength = strlen($line);
$randomString = '';
if ($chars >= 3 && $chars <= 8) {
for ($i = 0; $i < $words; $i ) {
$randomString = $line[rand(0, $charactersLength - 1)];
}
}
}
fclose($fileRead);
}
return $randomString;
}
$myRandomString = randomStringWords(3, 4);
echo $myRandomString;
$myRandomString
should return 3 chars 4 words. Instead, returns one single random char.
Update: string example from file
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
If I pass words = 3
and chars = 4
the output should be random 3 words with 4 chars each:
asPd
Plwi
OGfw
If I pass words = 3
and chars = 3
the output should be random 3 words with 3 chars each:
yYd
asd
Ikl
and so on..
CodePudding user response:
You are nearly where you want to be. Just little things and it should work.
$randomString = '';
if ($chars >= 3 && $chars <= 8) {
for ($i = 0; $i < $words; $i ) { // first loop over how many words you need
for ($j = 0; $j < $chars; $j ) { // then we loop over the needed chars
$randomString .= $line[rand(0, $charactersLength - 1)]; // .= to add to the existing string
}
$randomString .= ' '; // add a space after each word, you could also add each word to an array here
}
}
Let's go over my code comments:
- You only had one loop for words, not considering the number of wanted chars. Adding a second loop for the chars will fix this
$randomString = ...
will redeclare the whole variable, that's why you only got one single char as output..=
will add a string to an existing string, just like=
will add a number to an existing number.- Each time after the inner loop (the chars) is complete you need to add a space to it to make it a word (or add it to an array of words).
Tip
The PHP function file_get_contents
could be more suitable in your case since the file content is only one line. https://www.php.net/manual/en/function.file-get-contents