Forum Moderators: coopster

Message Too Old, No Replies

how to edit file's contents with php(insert line in between)

insert a line in between 2 lines in a file

         

rei15

3:36 am on Jul 11, 2006 (gmt 0)

10+ Year Member



i have a file with the contents of :

apple1
orange2
lime3
strawberry4
pineapple5
mango6

i would like to insert one newline "newline" in between "lime3" and "strawberry4"

first i wrote my code like this:


<?php

$fp = fopen("data/file.txt", "r+");

while($buf = fgets($fp)){
if(preg_match("/strawberry/", $buf)){
fputs($fp, "newline\n");
}
}
?>


but it ended up like this:

apple1
orange2
lime3
strawberry4
newline
e5
mango6

so i changed my code to the following (omitting \n at the end of "newline")


<?php

$fp = fopen("data/file.txt", "r+");

while($buf = fgets($fp)){
if(preg_match("/strawberry/", $buf)){
fputs($fp, "newline");
}
}
?>

but i got the result of


apple1
orange2
lime3
strawberry4
newlinele5
mango6

i cant seem to have a line inserted in between..
it replaces the line after it..

i would appreciate any help
thanks

the_nerd

4:26 pm on Jul 11, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You probably won't needs reg exprs for this. Just use

stripos ( string haystack, string needle [, int offset] )

to find where you want to insert your new string/line

then use

substr ( string string, int start [, int length] )

to get the part before the first match and one more time substr () to get the rest of the string. In between to add the new line.

$new = substr (...) . $mynewline . substr (....)