A user selects a number "$Num = $_POST['Number']" from a drop down to delete a line from a text file. Ex.
Cat
Dog
Mouse
Lets say they chose line 3. How do I delete the line in the file so it just prints:
Cat
Dog
using only the number they chose and not the actual words in the line?
asked May 8, 2017 at 23:31
Cvm192Cvm192
231 silver badge4 bronze badges
1
Use this:
$row_number = 0; // Number of the line we are deleting
$file_out = file["file.txt"]; // Read the whole file into an array
//Delete the recorded line
unset[$file_out[$row_number]];
//Recorded in a file
file_put_contents["file.txt", implode["", $file_out]];
answered May 8, 2017 at 23:44
5
- Table of contents
- How to delete a line from the file with php?
- How to delete a single line in a txt file with php [duplicate]
- How to delete a specific line from a file starting a string in php
- yjajkiew / php-delete-line-in-file Public
- PHP delete or replace a line from a text file
- How to delete a file using PHP ?
- How to delete text from file using preg_replace[] function in PHP ?
- C Program to Delete a Specific Line From a Text File
- Using php delete line from txt file.
How to delete a line from the file with php?
$contents = file_get_contents[$dir]; $contents = str_replace[$line, '', $contents]; file_put_contents[$dir, $contents];
$DELETE = "the_line_you_want_to_delete"; $data = file["./foo.txt"]; $out = array[]; foreach[$data as $line] { if[trim[$line] != $DELETE] { $out[] = $line; } } $fp = fopen["./foo.txt", "w+"]; flock[$fp, LOCK_EX]; foreach[$out as $line] { fwrite[$fp, $line]; } flock[$fp, LOCK_UN]; fclose[$fp];
function remove_line[$file, $remove] { $lines = file[$file, FILE_IGNORE_NEW_LINES]; foreach[$lines as $key => $line] { if[$line === $remove] unset[$lines[$key]]; } $data = implode[PHP_EOL, $lines]; file_put_contents[$file, $data]; }
$contents = file_get_contents[$dir]; $new_contents = ""; if [strpos[$contents, $id] !== false] { // if file contains ID $contents_array = explode[PHP_EOL, $contents]; foreach [$contents_array as &$record] { // for each line if [strpos[$record, $id] !== false] { // if we have found the correct line continue; // we've found the line to delete - so don't add it to the new contents. } else { $new_contents .= $record . "\r"; // not the correct line, so we keep it } } file_put_contents[$dir, $new_contents]; // save the records to the file echo json_encode["Successfully updated record!"]; } else { echo json_encode["failed - user ID ". $id ." doesn't exist!"]; }
$line=explode["\r\n",$text]; unset[$line[0]]; $text=implode["\r\n",$line];
/** * Removes the first found line inside the given file. * * @param string $line The line content to be searched. * @param string $filePath Path of the file to be edited. * @param bool $removeOnlyFirstMatch Whether to remove only the first match or * the whole matches. * @return bool If any matches found [and removed] or not. * * @throw \RuntimeException If the file is empty. * @throw \RuntimeException When the file cannot be updated. */ function removeLineFromFile[ string $line, string $filePath, bool $removeOnlyFirstMatch = true ]: bool { // You can wrap it inside a try-catch block $file = new \SplFileObject[$filePath, "r"]; // Checks whether the file size is not zero $fileSize = $file->getSize[]; if [$fileSize !== 0] { // Read the whole file $fileContent = $file->fread[$fileSize]; } else { // File is empty throw new \RuntimeException["File '$filePath' is empty"]; } // Free file resources $file = null; // Divide file content into its lines $fileLineByLine = explode[PHP_EOL, $fileContent]; $found = false; foreach [$fileLineByLine as $lineNumber => $thisLine] { if [$thisLine === $line] { $found = true; unset[$fileLineByLine[$lineNumber]]; if [$removeOnlyFirstMatch] { break; } } } // We don't need to update file either if the line not found if [!$found] { return false; } // Join lines together $newFileContent = implode[PHP_EOL, $fileLineByLine]; // Finally, update the file $file = new \SplFileObject[$filePath, "w"]; if [$file->fwrite[$newFileContent] !== strlen[$newFileContent]] { throw new \RuntimeException["Could not update the file '$filePath'"]; } return true; }
// $dir is your filename, as you mentioned removeLineFromFile[$line, $dir];
$fileLineByLine[$lineNumber] = ""; // Or even $fileLineByLine[$lineNumber] = null;
unset[$fileLineByLine[$key]];
$file = fopen["path/to/file", "a+"]; // remove 2nd and 3rd lines [line numbers are one-based] fremove_line[$file, 2, 3]; fclose[$file];
/** * Remove the lines with the given `$line_number` from the `$file`. * * Example: * ```php * $file = fopen["path/to/file", "a+"]; * // remove lines 1 and 2 * fremove_line[$file, 1, 2]; * fclose[$file]; * ``` * * @param resource $file The file resource opened by `fopen[]` * @param int ...$line_number The one-based line number[s] to remove, if the * line does not exist, it is ignored * * @return boolean True on success, false on failure */ function fremove_line[$file, int ...$line_number]: bool{ // set the pointer to the start of the file if[!rewind[$file]]{ return false; } // get the stat for the full size to truncate the file later on $stat = fstat[$file]; if[!$stat]{ return false; } $current_line = 1; // change to 0 for zero-based $line_number $byte_offset = 0; while[[$line = fgets[$file]] !== false]{ // the bytes of the lines ["number of ASCII chars"] $line_bytes = strlen[$line]; if[$byte_offset > 0]{ // move lines upwards // go back the `$byte_offset` fseek[$file, -1 * [$byte_offset + $line_bytes], SEEK_CUR]; // move the line upwards, until the `$byte_offset` is reached if[!fwrite[$file, $line]]{ return false; } // set the file pointer to the current line again, `fwrite[]` added `$line_bytes` // already fseek[$file, $byte_offset, SEEK_CUR]; } if[in_array[$current_line, $line_number]]{ // the `$current_line` should be removed so save to skip the number of bytes $byte_offset += $line_bytes; } // keep track of the current line $current_line++; } // remove the end of the file return ftruncate[$file, $stat["size"] - $byte_offset]; }
file_put_contents[$filename, str_replace[$line . "\r\n", "", file_get_contents[$filename]]];
How to delete a single line in a txt file with php [duplicate]
[email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected],
$content = file_get_contents['database-email.txt']; $content = str_replace['[email protected],', '', $content]; file_put_contents['database-email.txt', $content];
$emailToRemove = "[email protected]"; $contents = file['database-email.txt']; //Read all lines $contents = array_filter[$contents, function [$email] use [$emailToRemove] { return trim[$email, " \n\r,"] != $emailToRemove; }]; // Filter out the matching email file_put_contents['database-email.txt', implode["\n", $contents]]; // Write back
$emailToRemove = "[email protected]"; $fh = fopen['database-email.txt', "r"]; //Current file $fout = fopen['database-email.txt.new', "w"]; //New temporary file while [[$line = fgets[$fh]] !== null] { if [trim[$line," \n\r,"] != $emailToRemove] { fwrite[$fout, $line, strlen[$line]]; //Write to new file if needed } } fclose[$fh]; fclose[$fout]; unlink['database-email.txt']; //Delete old file rename['database-email.txt.new', 'database-email.txt']; //New file is old file
$DELETE = "[email protected]"; $data = file["database-email.txt"]; $out = array[]; foreach[$data as $line] { if[trim[$line] != $DELETE] { $out[] = $line; } } $fp = fopen["database-email.txt", "w+"]; flock[$fp, LOCK_EX]; foreach[$out as $line] { fwrite[$fp, $line]; } flock[$fp, LOCK_UN]; fclose[$fp];
$data = ""; $emailsToRemove = ["[email protected]" , "[email protected]"]; //open to read $f = fopen['databse-email.txt','r']; while [$line = fgets[$f]] { $emailWithComma = $line . ","; //check if email marked to remove if[in_array[$emailWithComma , $emailsToRemove]] continue; $data = $data . $line; } fclose[$f]; //open to write $f = fopen['databse-email.txt','w']; fwrite[$f, $data]; fclose[$fh];
$file = "file_name.txt"; $search_for = "example_for_remove"; $file_data = file_get_contents[$file]; $pattern = "/$search_for/mi"; $file_data_after_remove_word = preg_replace[$pattern, '', $file_data]; $file_data_after_remove_blank_line = preg_replace["/[^[\r\n]*|[\r\n]+][\s\t]*[\r\n]+/", "\n", $file_data_after_remove_word]; file_put_contents[$file,$file_data_after_remove_blank_line];
How to delete a specific line from a file starting a string in php
abc samle sample this abc sample xyz test sample sample
abc samle sample xyz test sample sample
yjajkiew / php-delete-line-in-file Public
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE Version 1, August 2012 Yann Jajkiewicz Everyone is permitted to copy and distribute verbatim or modified copies of this program. DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. You just DO WHAT THE FUCK YOU WANT TO.
PHP delete or replace a line from a text file
while[!feof[$file]] { $data=fgets[$file]."
"; $data1="++ gateway1"; if[$data==$data1] { echo "found"; } }
How to delete a file using PHP ?
unlink[ $filename, $context ];
gfg.txt has been deleted
Warning: unlink[] expects parameter 1 to be a valid path, resource given in C:\xampp\htdocs\server.php on line 12 Resource id #3 cannot be deleted due to an error
How to delete text from file using preg_replace[] function in PHP ?
preg_replace[ $pattern, $replacement, $subject];
mango apple papaya guava apple grapes mango apple
File contents before using preg_replace[] function mango apple papaya guava apple grapes mango apple File contents after using preg_replace[] function
File contents before using preg_replace[] function mango apple papaya guava apple grapes mango apple File contents after using preg_replace[] function mngo pple ppy guv pple grpes mngo pple
File contents before using preg_replace[] function mango apple papaya guava apple grapes mango apple File contents after using preg_replace[] function mango papaya guava grapes mango
C Program to Delete a Specific Line From a Text File
#include int main[] { FILE *fp1, *fp2; //consider 40 character string to store filename char filename[40]; char c; int del_line, temp = 1; //asks user for file name printf["Enter file name: "]; //receives file name from user and stores in 'filename' scanf["%s", filename]; //open file in read mode fp1 = fopen[filename, "r"]; c = getc[fp1]; //until the last character of file is obtained while [c != EOF] { printf["%c", c]; //print current character and read next character c = getc[fp1]; } //rewind rewind[fp1]; printf[" \n Enter line number of the line to be deleted:"]; //accept number from user. scanf["%d", &del_line]; //open new file in write mode fp2 = fopen["copy.c", "w"]; c = getc[fp1]; while [c != EOF] { c = getc[fp1]; if [c == '\n'] temp++; //except the line to be deleted if [temp != del_line] { //copy all lines in file copy.c putc[c, fp2]; } } //close both the files. fclose[fp1]; fclose[fp2]; //remove original file remove[filename]; //rename the file copy.c to original name rename["copy.c", filename]; printf["\n The contents of file after being modified are as follows:\n"]; fp1 = fopen[filename, "r"]; c = getc[fp1]; while [c != EOF] { printf["%c", c]; c = getc[fp1]; } fclose[fp1]; return 0; }