I'm trying to figure out how to skip the first and last line of a text file when I'm reading it while using fgets(). The first line could be solved with an if(!$firstLine), but I'm not sure how to ignore the last line or if my solution for ignoring the first line is the best choice.
fgets($file); //Ignore the first line
$line = fgets($file);
$next = fgets($file);
while ($next !== false) { //check the line after the one you will process next.
//This way, when $next is false, then you still have one line left you could process, the last line.
//Do Stuff
$line = $next;
$next = fgets($file);
}
$lines = file('http://www.example.com/');//or local file
unset($lines[0]);
unset($lines[count($lines)-1)]);
$new_file = implode('', $lines); //may want to use line break "\n" for the join
You might want to try exploding the file contents. It will help you alot! After that you will label it.
Unfortunately, file() will open file into "serial" stream (not sure if serial is right word), it means that you must read full file before detecting his end
try this
$str= file_get_contents("file.txt");
$arr = preg_split ("\n",$str);
$n = count($arr);
$n is a number of lines
$str="";
for($i=0;$i<$n;$i++){
if($i>0 && $i<($n-1)){ $str.=$arr[$i]}
}
/**Str without line 1 and final line */
Related
hope that you're doing well, I'm trying to implement a script so that I can use it to replace a line with another one in a file, I tried a lot of PHP scripts and Bash codes but they all seem to failed, here what I tried last:
function replace_a_line() {
$line=3; //includes zero as 1.
$newdata='this is a test 123';
$data=file('./txt.txt');
$data[$line]=$newdata."\r\n";
$data=implode($data);
file_put_contents('./txt.txt',$data);
}
My file name is txt.txt
Thank you in advance
I think you almost did it. No need to implode it yourself. file_put_contents does it for you.
Add additional checks to make sure line number is something within the number of lines range or append the text to the end.
<?php
function replace_a_line($line = 3,$new_str = 'Your text') {
$data = file('test.txt');
if($line >= count($data)) $data[] = $new_str;
else $data[ $line - 1] = $new_str . "\n";
return file_put_contents('test.txt', $data, LOCK_EX);
}
replace_a_line();
I have a text file with line breaks that I have already imploded in to single line and added commas to the end of every line.
I need to remove every 36th comma from the line and add line break as well.
this is my code:
$lines = file("filename.txt", FILE_IGNORE_NEW_LINES);
$comma_separated = implode(",", $lines);
$lines2 = preg_replace('/(?:[^,]*,){36}/', '$0\r\n', $comma_separated);
I have always had trouble with coding. My brains just don't go that way. I try my best, and I am 100 % sure I have searched and read the solution, but I have not understood it.
I would rather do something like this.
Instead of a regex that will eventually fail, add a string to every 36 line before you implode.
This string can easily be found with a simple str_replace() to remove and add the line break.
$lines = file("filename.txt", FILE_IGNORE_NEW_LINES);
For($i=0; $i<count($lines);){
$lines[$i] .= "something";
$i = $i+36;
}
$comma_separated = implode(",", $lines);
// String replace something to line break.
$result = str_replace("something,", "<br>", $comma_separated);
Edit sorry the string replace of course needs to go after the implode.
Sorry for the confusion.
$lines = file("filename.txt", FILE_IGNORE_NEW_LINES);
For($i=0; $i<count($lines);){
//your code
if($i%36==0){
trim($line,',');
}
}
I'm trying to figure out how to skip the first and last line of a text file when I'm reading it while using fgets(). The first line could be solved with an if(!$firstLine), but I'm not sure how to ignore the last line or if my solution for ignoring the first line is the best choice.
fgets($file); //Ignore the first line
$line = fgets($file);
$next = fgets($file);
while ($next !== false) { //check the line after the one you will process next.
//This way, when $next is false, then you still have one line left you could process, the last line.
//Do Stuff
$line = $next;
$next = fgets($file);
}
$lines = file('http://www.example.com/');//or local file
unset($lines[0]);
unset($lines[count($lines)-1)]);
$new_file = implode('', $lines); //may want to use line break "\n" for the join
You might want to try exploding the file contents. It will help you alot! After that you will label it.
Unfortunately, file() will open file into "serial" stream (not sure if serial is right word), it means that you must read full file before detecting his end
try this
$str= file_get_contents("file.txt");
$arr = preg_split ("\n",$str);
$n = count($arr);
$n is a number of lines
$str="";
for($i=0;$i<$n;$i++){
if($i>0 && $i<($n-1)){ $str.=$arr[$i]}
}
/**Str without line 1 and final line */
i need to generate random sentences from dictionary. In dictionary is every word at one line, firstly i load this dictionary to array and after it i have a for cycle and randomly pickup some data, but if i wrote it, so it is at one line in browser, but in source code is every word at another line. Then I need to create a set of XML files from search engine and this new lines are indexed as /n/r and in XML source code it has got a symbol
So my question is how i can make a sentence which will be at one line in source code too. Thanks.
Here is piece of my code i donĀ“t have here randomly loading data, i only made it for illustration in for cycle.
$file = fopen("test.txt", "r");
$data = array();
while (($buffer = fgets($file)) !== false) {
$data[] = $buffer;
}
$sentence = '';
for ($i=0;$i<10;$i++){
$sentence = $sentence . $data[$i];
}
Use trim function to filter new line characters.
In your code use:
$data[] = trim($buffer);
when i try to insert each line into my oracle database i get an error stating invalid number, but if have only one line in the file it works fine.
$file = #fopen('file.text', "r") ;
// while there is another line to read in the file
while (!feof($file))
{
// Get the current line that the file is reading
$currentLine = fgets($file) ;
$currentLine = explode(' ',$currentLine) ;
insert($currentLine) ;
}
fclose($file) ;
the lines look like this
1 4 100
1 4 101
Try this:
$currentLine = trim(fgets($file));
It's possibly failing on the newline/carriage-return at the end of the line.
If not, where is this insert() function defined? Build a debug section that echos or writes out the attempted queries so you can really see the issue.
Your explode() call is using 9 spaces as a separator, but your file only appears to have 5 spaces between each number. This means your $currentline be a single element array containing the original line, and not separate elements with a number in each.
Either change the number of spaces in the explode call, or change to
$currentLine = preg_split('/\s+/', $currentLine);
which will split on any number of sequential spaces.
I would double check that there is not a new line at the end of the file. Maybe even double check inside of php that the line read is not blank.
$lineCount=0;
// while there is another line to read in the file
while (!feof($file))
{
$lineCount++;
// Get the current line that the file is reading
$currentLine = fgets($file);
if(trim($currentLine) != ''){
$currentLine = explode(' ',$currentLine) ;
insert($currentLine) ;
echo "Inserted line number $lineCount<br />";
} else {
echo "There was a blank line at line number $lineCount.<br />";
}
}
$lines = explode("\n", str_replace("\r", "", file_get_contents("file.text")));
foreach ($lines as $line)
{
insert(explode(' ', $line);
}
try this :
// Read all data in the file
$file_all = file_get_contents('file.text') or die("unable to open file");
// create an array with each index = a line
$file_lines = explode(chr(13),$file_all);
// Insert each line found
foreach ($file_lines as $file_line) { insert($file_line); };