jamiet147 Posted June 10, 2009 Share Posted June 10, 2009 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"; } ?> Link to comment https://forums.phpfreaks.com/topic/161658-php-to-replace-text-instead-of-deleting-it/ Share on other sites More sharing options...
Mark Baker Posted June 10, 2009 Share Posted June 10, 2009 change //remove the line unset($arr["$lineToDelete"]); to //remove the line $arr["$lineToDelete"]=""; Link to comment https://forums.phpfreaks.com/topic/161658-php-to-replace-text-instead-of-deleting-it/#findComment-853018 Share on other sites More sharing options...
jamiet147 Posted June 10, 2009 Author Share Posted June 10, 2009 Thank you so much! worked first time no problems Many Thanks Jamie Link to comment https://forums.phpfreaks.com/topic/161658-php-to-replace-text-instead-of-deleting-it/#findComment-853388 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.