Jump to content

replace line in file


doddsey_65

Recommended Posts

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?

 

Link to comment
https://forums.phpfreaks.com/topic/235698-replace-line-in-file/
Share on other sites

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.