doddsey_65 Posted May 6, 2011 Share Posted May 6, 2011 hi, im using the following code to read the content of a file, and then add a line to the end of the file. $file = dirname(dirname(dirname(__FILE__))).'/includes/settings.php'; $read = fopen($file, 'r')or die('Opening Error'); $content = fread($read, filesize($file)); fclose($read)or die('Close Error'); if(isset($_POST['cat_bg'])) { $write = fopen($file, 'w')or die('Opening Error'); $cat_bg = $_POST['cat_bg']; $new_content = $content.'$color[\'cat_header\'][\'background\'] = '.$cat_bg.';'; fwrite($write, $new_content)or die('Write Error'); fclose($write); } however i would like to delete a line from the file before the content in inserted as the new line i am inserting is a duplicate variable with a different value. Can anyone help? Quote Link to comment https://forums.phpfreaks.com/topic/235698-replace-line-in-file/ Share on other sites More sharing options...
MadTechie Posted May 6, 2011 Share Posted May 6, 2011 It maybe easier to read the file into an array, then concatenate it back to a string for example <?php $myfile = 'myFile.txt'; $lines = file($myfile); if(isset($_GET['Remove'])){ //remove line unset($lines[$_GET['Remove']]); //save file file_put_contents($myfile, implode("/n",$lines)); } if(isset($_GET['add'])){ //add line $lines[] = "this is a new line"; //save file file_put_contents($myfile, implode("/n",$lines)); } //display file foreach ($lines as $line_num => $line) { echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "[<a href='?Remove={$line_num}'>Remove</a>] [<a href='?add=true'>Add</a>]<br />\n"; } Edit: fixed a typo EDIT: just added "add line" your get what i mean Quote Link to comment https://forums.phpfreaks.com/topic/235698-replace-line-in-file/#findComment-1211435 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.