How can i only echo 5 lines?
<?php
$text = Here i have a long long long text about 20 lines;
echo $text;
?>
So and i want something like that.->
TEXTLINE 1
TEXTLINE 2
TEXTLINE 3
TEXTLINE 4
TEXTLINE 5
And than stop.
Code for the mentioned text of Harri (at least this would be my approach):
$strings = explode(" ", $text);
for($i=0; $i<$your_lines; $i++) {
echo $strings[$i] . " ";
}
Explode the string to array, then loop through the array until last line you want to print. Printh each line while looping the array.
when you need lines (not words) use
$lines = explode(PHP_EOL, $text);
Assuming the output is a web browser, then this is a display issue, since what you are referring to as "line" depends on the width/height of the container. (It's not very clear what you try to ask)
You can set a width and height on a div using css and use overflow hidden on that to achieve a result like the one you want
demo
http://jsfiddle.net/g5Y5c/
.mydiv {width:100px;height:100px;overflow:hidden;}
Related
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
"
Needed solution:
I am working with a simple PHP script that should:
Add "value4:::" at the end of the first line in a file
Add ":::" at the end of all the next lines
I am novise in programming, and have sit here for two days trying to figure this out. Might be a little detail, or it might be totally wrong way of doing this task.
It might be wrong way to do this, or may be a regex problem? I really don't know.
I kindly ask you to help me with the solution.
Information:
The file newstest.db looks like this:
ID:::value1:::value2:::value3:::
1:::My:::first:::line:::
2:::My:::second:::line:::
3:::Your:::third:::line:::
And using this php script I'd like to make it look like this:
ID:::value1:::value2:::value3:::value4:::
1:::My:::first:::line::::::
2:::My:::second:::line::::::
3:::Your:::third:::line::::::
Problem:
So far I have almost got it, but I am confused to why it adds the "value4:::" to the beginning of the second line, and then add ":::" at the beginning (not end) of all of the rest of the lines.
So I get a file that looks like this:
ID:::value1:::value2:::value3:::
value4:::1:::My:::first:::line:::
:::2:::My:::second:::line:::
:::3:::Your:::third:::line:::
I thought that:
$lineshere = 'Some text here:::';
$lines1 = $linehere.'value4:::';
would output "Some text here:::value4:::"
May be the problem is due to this way of adding line after line?
$lines = '';
$lines.= 'My test';
$lines.= ' is here';
echo $lines;
I am a novise in programming, so I might have used totally wrong functions tec to make this work.
But in this case it seams to add a space or line break/ line end in the wrong place.
My try on this solution:
<?php
// specify the file
$file_source="newstest.db";
// get the content of the file
$newscontent = file($file_source, true);
//set a start value (clear memory)
$lines ='';
// get each line and treat it line by line.
foreach ($newscontent as $line_num => $linehere) {
// add "value4:::" at the end of FIRST line only, and put it in memory $lines
if($line_num==0) {
$lines.= $linehere.'value4:::';
// Just to see what the line looks like
//echo 'First line: '.$lines.'<br /><br />';
}
// then add ":::" to the other lines and add them to memory $lines
if($line_num>0) {
$lines1 = $linehere.':::';
$lines.= $lines1;
//just look at the line
//echo 'Line #'.$line_num.': '.$lines1.'<br /><br />';
}
}
//Write new content to $file_source
$f = fopen($file_source, 'w');
fwrite($f,$lines);
fclose($f);
echo "// to show the results ar array<br /><br />";
$newscontentlook = file($file_source, true);
print_r(array_values($newscontentlook));
?>
This is actually very easy to achieve with file_get_contents and preg_replace, i.e:
$content = file_get_contents("newstest.db");
$content = preg_replace('/(^ID:.*\S)/im', '$1value4:::', $content);
$content = preg_replace('/(^\d+.*\S)/im', '$1:::', $content);
file_put_contents("newstest.db", $content);
Output:
ID:::value1:::value2:::value3:::value4:::
1:::My:::first:::line::::::
2:::My:::second:::line::::::
3:::Your:::third:::line::::::
Ideone Demo
the function file() gives you the file in an array with each line being an element of the array. Each ending of the line (EOL) is included in the elements. So appending text to that line will be after the EOL, and thus effectively on the beginning of the next line.
You can either choose to not use file() and explode the text yourself on the EOL, so the EOL is no longer part of the array element. Then edit the elements, and implode the array again.
Or fopen() the file, and fread() through it yourself. The latter option is preferred, as it won't load the entire file into memory at once.
I think the problem is in your loop through the lines read by file() function:
foreach ($newscontent as $line_num => $linehere) {
...
$linehere contains a newline at the end, so you should simply chop it before using it:
foreach ($newscontent as $line_num => $linehere) {
$linehere = chop($linehere);
...
If you don't chop the line contents, when you concatenate a string to it, you'll get:
LINE_CONTENTS\nSTRING_ADDED
which, when printed, will be:
LINE_CONTENTS
STRING_ADDED
Hope this helps...
I want to change Text1 to Text2.
Text1
Test1 is here<br>Now comes Test2<br>Then test 3<br><br>Thats it.
Text2
Test1 is here<br><br>Now comes Test2<br><br>Then test 3<br><br><br>Thats it.
i.e; add extra 'breakline' tag to the existing one in a string.
I tried it with preg_replace but can't figure it the way I wanted.
My Try -
preg_replace('/(?:(?:<br>)\s*)/s', "<br><br>", $posttext)
This should do it:
$text = preg_replace('/((<br>(\s+)?)+)/', '$1<br>', $text);
If you don't want to allow for newlines and spaces try: /((<br>)+)/
Try this:
preg_replace('/((?:<br>)+)\s*/s', "$1<br>", $posttext);
This captures a sequence of <br> tags, optionally followed by whitespace, and then adds one more after them.
DEMO
try this.
$text1 = "Test1 is here<br>Now comes Test2<br>Then test 3<br><br>Thats it.";
$text2 = substr($text1,0,strripos($text1,"<br>")) ."<br>" . substr($text1,strripos($text1,"<br>"));
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);
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.