How to delete a line from the file with php?

后端 未结 9 1361
北荒
北荒 2020-11-27 19:36

I have a file named $dir and a string named $line, I know that this string is a complete line of that file but I don\'t know its line number and I

相关标签:
9条回答
  • 2020-11-27 20:02

    This is also good if you're looking for a substring (ID) in a line and want to replace the old line with the a new line.

    Code:

    $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!");
    }
    

    Example:

    input: "123,student"

    Old file:

    ID,occupation

    123,student

    124,brick layer

    Running the code will change file to:

    New file:

    ID,occupation

    124,brick layer

    0 讨论(0)
  • 2020-11-27 20:06

    Another approach is to read the file line by line until you find a match, then truncate the file to that point, and then append the rest of the lines.

    0 讨论(0)
  • 2020-11-27 20:07

    Like this:

    file_put_contents($filename, str_replace($line . "\r\n", "", file_get_contents($filename)));
    
    0 讨论(0)
  • 2020-11-27 20:08
    $contents = file_get_contents($dir);
    $contents = str_replace($line, '', $contents);
    file_put_contents($dir, $contents);
    
    0 讨论(0)
  • 2020-11-27 20:13

    It can be solved without the use of awk:

    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);
    }
    
    0 讨论(0)
  • 2020-11-27 20:17

    this will just look over every line and if it not what you want to delete, it gets pushed to an array that will get written back to the file. see this

     $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);  
    
    0 讨论(0)
提交回复
热议问题