Forum Moderators: coopster
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");
}
}
?>
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
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 (....)