PHP "while" loop is not executing second command for each loop - php

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?

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>";

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
"

Related

PHP echoing variable but adding line breaks

I have a variable a such $var:
$var = "One, Two, Three";
I can echo the variable without any problems the output is:
One, Two, Three
Is it possible, when echoing the variable to add a line break where there is a ,, so it would look like this?
One,
Two,
Three
If you echo the text to HTML, you can do the following:
echo str_replace(",", ", <br/>", $var);
If you echo the string to a console or a text file through redirection, just use the PHP_EOL constant, which represents the correct end-of-line string for the current platform ie. "\n" for Unix, "\r\n" for Windows:
echo str_replace(",", "," . PHP_EOL, $var);
You can use this:
$var = "One,\nTwo,\nThree";
\n is the line break, and makes sense if you are working through the terminal
You use \n to force a new line when outputting to a terminal.
$var = "One,\nTwo,\nThree";
You can use the HTML <br /> to output a new line on a web browser.
$var = "One,<br />Two,<br />Three";
You can use the str_replace function once you determine which type you want.
Make use of <br> tag
$var = "One, <br>Two, <br>Three";
(or) Make use of str_replace in PHP
<?php
$var = "One, Two, Three";
echo str_replace(',',',<br>',$var); // code replaces all your commas with , and a <br> tag
Explode the string with the comma as separator, then iterate through the resulting array, adding line breaks (with the br tag if outputting to browser, or newline (\n) escape sequence if outputting to terminal) when needed?

how to combine function and string inside php echo

Can you combine a PHP function and string in the same echo statement? Currently, I have this code that grabs a photo's caption, then shortens it to 25 characters or less, stopping at the nearest blank space so it can fit the whole word.
echo substr($caption,0,strpos($caption,' ',25));
echo " ...";
Example output: changes "This is way too long to fit in this foobar small area preview box" to "This is way too long to..."
I'd like to be able to combine the 'substr' and '...' into the same echo statement. I tried the following, but it didn't work:
echo "{substr($caption,0,strpos($caption,' ',25))} ...";
Any ideas?
The , is great for this, and much faster than the ., which has the overhead of concatenating the string.
echo substr($caption, 0, strpos($caption, ' ', 25)), '...';
EDIT: To clarify, the , just simply sends all the strings, separated by the comma, to echo, and thus is equal to the separate line echo statments. The DOT operator performs concatenation. You can use as many commas as you want, i.e. echo strFunction1(), ' some text ', strFunction2(), '...';
Try:
echo substr($caption,0,strpos($caption,' ',25)) . '...';

Using PHP to Seperate Results of a txt file

I am trying to display the last 10 lines of a File and from there take those results and break them down to 10 individual lines..
Currently the code I have found from examples is:
$filearray = file("test.txt");
$lastfifteenlines = array_slice($filearray,-10);
echo implode($lastfifteenlines, "\n")
It display's the 10 items I need however it does not break them down onto individual lines the current results are:
1.0.0.11 1.0.0.12 1.0.0.13 1.0.0.14 1.0.0.15
I need that to instead display as:
1.0.0.11
1.0.0.12
1.0.0.13
1.0.0.14
1.0.0.15
Thanks in Advance for the Asistance!
\n is plain whitespace in html.
use echo implode("<br>", $lastfifteenlines) or put them in to separate divs, use a list (ul+li), etc..
use the explode function, like this
$filearray = file("test.txt");
$lastfifteenlines = array_slice($filearray,-10);
$impfile = implode($lastfifteenlines, '\n');
$lines = explode('\n', $impfile);
foreach ($lines as $line){
echo $line."<br>";
}
outpu will be
1.0.0.11
1.0.0.12
1.0.0.13
1.0.0.14
1.0.0.15
i hope that's what you want :)
Your code works fine. You just can't see the line breaks because HTML doesn't treat them as line breaks.
See the HTML source code in your browser to see the line breaks.
Possible solution
echo <pre> and </pre> tags before and after the implode.
Add header("Content-Type: text/plain"); before any output. It will cause the browser to parse the document as a text file and not HTML (note that no HTML tags will be parsed by the browser)
implode the array with a different string, <br>, which will cause a line break in HTML.
Also, your syntax is wrong, it's
implode($glue, $pieces);
And not
implode($pieces, $glue);

Why is it starting a new line before it should in PHP array?

I'm having a problem with arrays and file writing, what I want to do is take one file, and copy it onto another file, except with formatting added to it.
To be specific, this:
Line 1
Line 2
Line 3
Would become this:
<br /><hr />Line 1
<br /><hr />Line 2
<br /><hr />Line 3
And I've sorta done that, but something weird happens. Instead of formatting all on one line, it linebreaks and keeps going. Like this
<br />1
THE END<br />7
THE END<br />0
THE END<br />Red
THE END<br />Silent
THE END<br />No ChangesTHE END
My code for this is:
<?php
$filename1 = "directorx_OLDONE.txt";
$filename2 = "directorx_NEWONE.txt";
$file1 = fopen($filename1, "r") or exit ("No");
$file2 = fopen($filename2, "w") or exit ("No");
while (!feof($file1)){
$listArrayf1[] = fgets($file1);
}
fclose($file1);
echo var_dump($listArrayf1) . "<br /><br />";
$entries = count($listArrayf1) - 1;
echo $entries;
for($i=0;$i<=$entries;$i++){
$listArrayf2[] = "<br />".$listArrayf1[$i]."THE END";
fwrite($file2, $listArrayf2[$i]);
}
fclose($file2);
echo var_dump($listArrayf2);
/*
Open file1, r
Open file2, w
While it's not the end of the file, add each line of file1 to an array.
Count the number of lines in file1 and call it Entries. -1 because gotta start at 0.
Make a new array with the values of the old one, but with tags before and after it.
*/
?>
I'm sure there's a better way to accomplish the ultimate goal I'm trying, which is detecting certain words entered into a form, (There's probably a better way than making a formatted and non-formatted copy of what gets entered.) but my PHP vocab is limited and I'd like to figure out the long, prerequisite hard ways before learning how to do em easier.
At first I thought that it was because I was writing the OLDFILE manually, using the return key. So I made a script to write it using \n instead and it changed nothing.
Eh :)
At first, please take a look on var_dump and check what the function is returning (nothing, so correct usage is var_dump( ...); echo "<br />";)
Second, fgets reads string including newline character, so I guess you see in your string something like this:
string( 10) "abcdefghi
"
So you have to remove newline manually for example with trim.
Next, I'd recommend to (at least) take a look at foreach.
So I'd wrote the whole loop as:
foreach( $listArrayf1 as $row){
$row = "<br /><hr />". trim( $row)."THE END";
fwrite($file2, $row);
$listArrayf2[] = $row;
}
You may also use foreach( $listArrayf1 as &$row) and in the end $listArrayf1 will contain exactly the same as $listArrayf2. When you need to preserve all other spaces, you should probably use $row = substr( $row, 0, -1);
btw: you can write normal code, mark it in textarea and by hitting ctrl+k it'll get indented by 4 spaces
fgets returns the newline character at the end of each line as part of its input. That's where your "extra" newline comes from.
Change this
$listArrayf1[] = fgets($file1);
to this:
$listArrayf1[] = rtrim(fgets($file1), "\r\n");
This will remove the newline characters from the end of the return value and make your strings format as intended.
However, as you said yourself you are really doing things in a roundabout way. You could read all of file1 into an array with just
$listArrayf1 = file($filename1);
That's it. No loops, no fopen, no problems with newlines. It pays to look for the most fitting way of doing things.

nl2br for paragraphs

$variable = 'Afrikaans
Shqip - Albanian
Euskara - Basque';
How do I convert each new line to paragraph?
$variable should become:
<p>Afrikaans</p>
<p>Shqip - Albanian</p>
<p>Euskara - Basque</p>
Try this:
$variable = str_replace("\n", "</p>\n<p>", '<p>'.$variable.'</p>');
The following should do the trick :
$variable = '<p>' . str_replace("\n", "</p><p>", $variable) . '</p>';
Be careful, with the other proposals, some line breaks are not catch.
This function works on Windows, Linux or MacOS :
function nl2p($txt){
return str_replace(["\r\n", "\n\r", "\n", "\r"], '</p><p>', '<p>' . $txt . '</p>');
}
$array = explode("\n", $variable);
$newVariable = '<p>'.implode('</p><p>', $array).'</p>'
<?php
$variable = 'Afrikaans
Shqip - Albanian
Euskara - Basque';
$prep0 = str_replace(array("\r\n" , "\n\r") , "\n" , $variable);
$prep1 = str_replace("\r" , "\n" , $prep0);
$prep2 = preg_replace(array('/\n\s+/' , '/\s+\n/') , "\n" , trim($prep1));
$result = '<p>'.str_replace("\n", "</p>\n<p>", $prep2).'</p>';
echo $result;
/*
<p>Afrikaans</p>
<p>Shqip - Albanian</p>
<p>Euskara - Basque</p>
*/
?>
Explanation:
$prep0 and $prep1: Make sure each line ends with \n.
$prep2: Remove redundant whitespace. Keep linebreaks.
$result: Add p tags.
If you don't include $prep0, $prep1 and $prep2, $result will look like this:
<p>Afrikaans
</p>
<p>Shqip - Albanian
</p>
<p>Euskara - Basque</p>
Not very nice, I think.
Also, don't use preg_replace unless you have to. In most cases, str_replace is faster (at least according to my experience). See the comments below for more information.
Try:
$variable = 'Afrikaans
Shqip - Albanian
Euskara - Basque';
$result = preg_replace("/\r\n/", "<p>$1</p>", $variable);
echo $result;
I know this is a very old thread, but I want to highlight, that suggested solutions can have some issues in HTML world:
They do not check whether there is already a p tag around respective paragraph. This can result in extra paragraphs. At least some browsers will then show this as extra paragraphs, meaning <p>line1<p>line2</p>line3</p> will result in 3 paragraphs, which may not be the intention.
In fact, there is a bunch of tags, that are not expected inside of p, as per the spec of phrasing content. Or rather there is a limited set of tags, tha can be.
They will change new lines inside tags, where you want to preserve new lines as is. pre and textarea are the ones, where you could generally want that. code, samp, kbd and var are an example of other common values, but technically it can be any tag with white-space CSS property set to either pre, pre-wrap, pre-line or break-spaces.
They usually only check for \r\n or just \r or \n, while there are actually more symbols, that would mean new line, and they also have respective HTML entities, which can easily occur in HTML string.
To "combat" these flaws, at least, to an extent, I've just released a nl2tag library, which can also "convert" new lines to <li> items and has an "improved" nl2br logic (mostly for the sake of whitespace retention).
It's far from perfect (check the readme for limitations), but should cover you in case of relatively simple HTML string.

Categories