Jump to content

PHP to replace text instead of deleting it


jamiet147

Recommended Posts

Hi all,

 

I have this code that deletes an line of text from a .txt file but can anyone help me tweak it so instead of deleting the line of text it replaces it with a blank character or just leaves a empty line.

 

Many thanks for your time!

 

Jamie

 


<?php

/* varibles */	
$item = $_GET['item'];

?>


<?php




// the file name, this can be a path also, like /path/to/myfile.txt
$fileName = "test.txt";

// the line to delete
$lineNum =   $item ;

delLineFromFile($fileName, $lineNum);


function delLineFromFile($fileName, $lineNum){
// check the file exists 
  if(!is_writable($fileName))
    {
    // print an error
    print "The file $fileName is not writable";
    // exit the function
    exit;
    }
  else
      {
    // read the file into an array    
    $arr = file($fileName);
    }

  // the line to delete is the line number minus 1, because arrays begin at zero
  $lineToDelete = $lineNum-1;

  // check if the line to delete is greater than the length of the file
  if($lineToDelete > sizeof($arr))
    {
      // print an error
    print "You have chosen a line number, <b>[$lineNum]</b>,  higher than the length of the file.";
    // exit the function
    exit;
    }


//remove the line
  unset($arr["$lineToDelete"]);


  // open the file for reading
  if (!$fp = fopen($fileName, 'w+'))
    {
    // print an error
        print "Cannot open file ($fileName)";
      // exit the function
        exit;
        }
  
  // if $fp is valid
  if($fp)
    {
        // write the array to the file
        foreach($arr as $line) { fwrite($fp,$line); }

        // close the file
        fclose($fp);
        }

echo "done, deleted line $item";
}

?>

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.