Page 1 of 1
Insert Text into Middle of Text File
Posted: Sun Mar 13, 2005 10:33 am
by pdoersch
Hello all, I am working on a little PHP project, and what i would like to do, is not to "append" text to the end of a file, not to write text to the begginging of the file, and not to overwrite the file, but I want to:
insert text into an arbatrary line of a file, not erasing anything else, just pushing the rest down a line.
This must be possible without saving it all into an array and putting it back line by line and inserting the extra one where i want it. There must be a better way. Thanks.
Posted: Sun Mar 13, 2005 10:43 am
by feyd
pdoersch wrote:This must be possible without saving it all into an array and putting it back line by line and inserting the extra one where i want it. There must be a better way.
nope.
Posted: Sun Mar 13, 2005 3:05 pm
by pdoersch
wow. ok then. looks like PHP could use an update.
Posted: Sun Mar 13, 2005 3:15 pm
by feyd
I don't see why. The need for such a function is probably pretty low, as most situations want to either prepend or append to a file. At any rate, the language would do pretty much exactly what you'd have to do anyways.
Posted: Sun Mar 13, 2005 3:28 pm
by Ambush Commander
Well, you can always use one of PHPs array functions to insert the extra value into the array instead of doing it manually with a loop.
Posted: Sun Mar 13, 2005 4:40 pm
by pdoersch
I came up with a working solution using arrays. I did the inserting manually though. I didn't look into array functions all that much. Any way it works.
Code: Select all
$date = date("U");
$title = stripslashes($_POST['title']);
$author = stripslashes($_POST['author']);
$article = stripslashes($_POST['article']);
$list = stripslashes($_POST['list']);
$file = fopen($date , "a" );
fwrite($file, "1\n" . $title . "\n" . $author . "\n" . $article);
// ====array part====
$array=file($list);
$countc=count($array);
$times=0;
$fileb=fopen($list,"w");
while ( $times <= $countc ) {
fwrite($fileb, $array[$times]);
if ($times == 2) {
fwrite($fileb, $date . "\n" . $title . "\n" . $author . "\n\n");
}
$times++;
}
feyd | Please use Code: Select all
tags where approriate when posting code. Read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]