I have a text file with three words in it; each on a separate row: child, toy, people. I am using the Laravel Str::plural() function to pluralize each word and display the results with line breaks.
It works perfectly when I use the words in my code without a file, as so:
$output1 = Str::plural('child');
$output2 = Str::plural('toy');
$output3 = Str::plural('person');
$string = $output1 . "\r\n" . $output2 . "\r\n" . $output3;
echo nl2br($string);
The result shows as follows:
children
toys
people
However, when I use a "while" loop through a file containing these words, it only pluralizes the last word.
This is the "while" loop code:
$myFile = new \SplFileObject("words.txt");
while (!$myFile->eof()) {
$string = Str::plural($myFile->fgets());
echo nl2br($string);
}
As you can see from the result, only the last word is pluralized:
child
toy
people
Since my loop has brackets {} I assumed that BOTH lines of codes execute for each loop but I guess in PHP it's not like that? Any idea how to fix my "while" loop?
CodePudding user response:
There may be some extra spaces or line-ending characters, so you'll need to trim the string before you pluralize it.
$str = trim($myFile->fgets()); // Remove white space from the word/line
$string = Str::plural($str);
However, the nl2br will not work since there are no longer any new lines, so you'll want to append the br to the words.
echo "$string<br>";
CodePudding user response:
I think you have written words in file on separate rows; It means that of the end of each row you have hidden symbols \r\n I can say it because "person" is pluralized correclty and there is no other words after that in your example. You can easy check it with debug or var_dump function;
echo var_dump($yourString);
You will see something like this
string(5) "toy
"