Writing to a specific line in a file
I want to be able to write to a file and always write on that line.
1 Hello
2 How are you
3 Good
4 I see
5 Banana
6 End
Using the function:
function filewriter($filename, $line, $text,$append) {
}
So append = add without overwriting the string and this is optional as it will add by default
so add:
filewriter ("bob.txt", 2, "Bobishere", true) or filewriter ("bob.txt", 2, "Bobishere")
output:
1 Hello
2 Bobishere
3 How are you
4 Good
5 I see
6 Banana
7 End
but if they are not added it looks like filewriter ("bob.txt", 2, "Bobishere", false)
output:
1 Hello
2 Bobishere
3 Good
4 I see
5 Banana
6 End
I was able to figure out how to overwrite the file or add it to the end of the document.
What the function currently looks like:
function filewriter($filename,$line,$text,$append){
$current = file_get_contents($filename);
if ($append)
$current .= $line;
else
$current = $line;
file_put_contents($file, $current);
}
source to share
Rewrite your function:
function filewriter($filename,$line,$text,$append){
$current = file_get_contents($filename);
//Get the lines:
$lines = preg_split('/\r\n|\n|\r/', trim($current));
if ($append)
{
//We need to append:
for ($i = count($lines); $i > $line; $i--)
{
//Replace all lines so we get an empty spot at the line we want
$lines[$i] = $lines[i-1];
}
//Fill in the empty spot:
$lines[$line] = $text;
}
else
$lines[$line] = $text;
//Write back to the file.
file_put_contents($file, $lines);
}
PSEUDOCODE
The logic of this system:
We have a list:
[apple, crocodile, door, echo]
We want to insert bee
on line 2. First, we will move all elements along line 2:
1: apple
2: crocodile
3: door
4: echo
5: echo //==> We moved 'echo' 1 spot backwards in the array
Further:
1: apple
2: crocodile
3: door
4: door //==> We moved 'door' 1 spot backwards in the array
5: echo
Then:
1: apple
2: crocodile //==> This is a useless spot now, so we can put "bee" here.
3: crocodile //==> We moved 'crocodile' 1 spot backwards in the array
4: door
5: echo
And then we put the "bee" on the line we want:
1: apple
2: bee //==> TADA!
3: crocodile
4: door
5: echo
Warning: arrays in PHP are zero based, so the first line is a string 0
. Remember this when using the above function!
source to share