PHP add line in between two lines in textfile - php

I need to insert a line in a textfile between two other lines:
1: 30-12:32 1
2: 30-12:34 1
3: 30-12:35 1
For an example I need to insert a line between 1 and 2 which says 30-12:34 0.
I have the code to calculate what needs to be inserted by looking at the previous number but I need help inserting the text.
Thank you

Use this and then
function replaceInFile($what, $with, $file){
$buffer = "";
$fp = file($file);
foreach($fp as $line){
$buffer .= preg_replace("|".$what."[A-Za-z_.]*|", $what.$with, $line);
}
fclose($fp);
echo $buffer;
file_put_contents($file, $buffer);
}
and then enter what as the line just before it in text and with as what you want after it.

Related

how to replace some part of text from the text file in php

I'm trying to delete/edit some portion of text from text file, like if I have 10 lines in my text file then I want to edit 5th line or delete 3rd line without affecting any other line.
Currently what I'm doing
1. open text file and read data in php variable
2. done editing on that variable
3. delete the content of text file.
4. write new content on it
but is there any way to doing that thing without deleting whole content or by just edit those content?
my current code is like this
$file = fopen("users.txt", "a+");
$data = fread($file, filesize("users.txt"));
fclose($file);
$newdata = str_replace($old, $new, $data);
file_put_contents("users.txt", "");
$file = fopen("users.txt", "a+");
fwrite($file, $newdata);
fclose($file);
You could shorten that to:
$data = file_get_contents("users.txt");
$newdata = str_replace($old, $new, $data);
file_put_contents("users.txt", $newdata);
$str = '';
$lines = file("users.txt");
foreach($lines as $line_no=>$line_txt)
{
$line_no += 1; // Start with zero
//check the line number and concatenate the string
if($line_no == 5)
{
// Append the $str with your replaceable text
}
else{
$str .= $line_txt."\n";
}
}
// Then overwrite the $str content to same file
// i.e file_put_contents("users.txt", $str);
I have added solution as per my understanding, Hope it will help!!!
You can work on each line:
$lines = file("users.txt");
foreach($lines as &$line){
//do your stufff
// $line is one line
//
}
$content = implode("", $lines);
//now you can save $content like before
If you've only got 10 lines in your text file, then unless they are very long lines you're changing the amount of physical I/O required to change the contents (disks will only read/write data one physical sector at a time - and the days of 512byte sectors are long gone).
Yes, you can modify a large file by only writing the sectors which have changed - but that requires that you replace the data with something the same size to prevent framing errors (in PHP using fopen with mode c+, fgets/fseek/fwrite/ftell, fclose).
Really the corect answer is to stop storing multivalued data in a text file and use a DBMS (which also solves the concurrency issues).

PHP, skip first and last line of a text file using fgets

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 */

How to read line by line in php

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); };

Explode function in PHP

I have the following notepad file;
dbName:
tableName:
numberOfFields:
I am trying to write a php app which assigns the value of dbName to $dbName, tableName to $tableName and numberOfFields to $numFields.
My code is:
$handle = #fopen("config.txt", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
list($dbName, $tableName, $numFields) = explode(":", "$buffer");
}
fclose($handle);
}
however, ":" doesn't work as there are line breaks in between dbName and table Name. How do I explode $buffer, keeping the line breaks in the notepad file?
Thank you.
Have a look at the file function. It takes care of opening and reading the file, and returns an array of lines from the file. You could then iterate through the array and operate on each line individually.
http://us.php.net/manual/en/function.file.php
you can do this:
$data=file_get_contents("file");
$s = preg_split("/\n\n+/m", $data);
print_r($s);
You can use the chr($INT); function to look for the line break in your explode call.
Your can find more on the chr function here:
http://php.net/manual/en/function.chr.php
Add you can find the ascii chars for line break at:
http://www.asciitable.com/
fgets returns only one line. There is no way $buffer would ever have all three items at once, so that assignment to list() is wrong. For the first line, explode() will return an array with two items: "dbName" (text before the colon) and "" (text after the colon).
Does this work:
list ($dbName, $tableName, $numFields) = explode (':', implode ('', file ('config.txt')));
If you're sure of the line contents, and the file will not grow arbitrarily large:
1 <?php
2
3 $handle = #fopen("config.txt", "r");
4 if ($handle) {
5 $buffer = "";
6 while (!feof($handle)) {
7 $buffer = $buffer . trim(fgets($handle, 4096));
8 }
9 fclose($handle);
10
11 list($dbName, $tableName, $numFields) = explode(":", $buffer);
12 }
13
14 ?>
The while loop will go through all the lines and concatenate onto the same buffer after removing whitespace. This leaves just the content separated by ":". This is now amenable to explode.
As Nicolas wrote, feof gets one line at a time, so the list assignment needs to happen outside the loop.

How do I read a text file into array of lines and display it using PHP?

I have text file that looks like this:
1 1 1 1
1 2 3 5
4 4 5 5
I want to read this text file into array of lines and display it. Can anyone help me do this?
This should get you going: php function file
<?php
$cont = file_get_contents("data.txt");
$lines = explode("\n",$cont); // $lines is now an array containing each line
// do something with data here
?>
make sure you use the correct line endings however as Windows uses \r\n and UNIX uses \n.
you can use fopen(), fgets(). see here
eg
$f=fopen("file","r");
if($f){
while (!feof($f)) {
$line = fgets($f, 4096);
print $line;
}
fclose($f);
}
You'd want to do something like this:
<?
$filename = "somefile.txt";
$arr = file($filename);
foreach($arr as $line){
print $line . "<br />";
}
?>
This one is working for me.
$array = explode("\n", file_get_contents('file.txt'));

Categories