php 如何用php从文件中删除一行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5712878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:18:08  来源:igfitidea点击:

How to delete a line from the file with php?

phpfileawkline

提问by ibrahim

I have a file named $dirand 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 want to remove it from file, what should I do?

我有一个名为的文件$dir和一个名为的字符串$line,我知道这个字符串是该文件的完整行,但我不知道它的行号,我想从文件中删除它,我该怎么办?

Is it possible to use awk?

可以使用awk吗?

采纳答案by Naveed Ahmad

$contents = file_get_contents($dir);
$contents = str_replace($line, '', $contents);
file_put_contents($dir, $contents);

回答by Ignacio Vazquez-Abrams

Read the lines one by one, and write all but the matching line to another file. Then replace the original file.

逐行读取行,并将除匹配行之外的所有行写入另一个文件。然后替换原来的文件。

回答by Thusitha Sumanadasa

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);  

回答by Nabi K.A.Z.

It can be solved without the use of awk:

不用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);
}

回答by mpen

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.

另一种方法是逐行读取文件,直到找到匹配项,然后将文件截断到该点,然后附加其余行。

回答by ChickenFeet

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.

如果您在一行中查找子字符串 (ID) 并希望用新行替换旧行,这也很好。

Code:

代码:

$contents = file_get_contents($dir);
$new_contents= "";
if( strpos($contents, $id) !== false) { // if file contains ID
    $contents_array = preg_split("/\r\n|\r|\n/", $contents);
    foreach ($contents_array as &$record) {    // for each line
        if (strpos($record, $id) !== false) { // if we have found the correct line
            pass; // 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"

输入:“123,学生”

Old file:

旧文件:

ID,occupation

123,student

124,brick layer

身、职业

123,学生

124,砖层

Running the code will change file to:

运行代码会将文件更改为:

New file:

新文件:

ID,occupation

124,brick layer

身、职业

124,砖层

回答by MAChitgarha

I think the best way to work with files is to edit them as strings.

我认为处理文件的最佳方法是将它们编辑为字符串。

First, get all lines of the file (the following codes can be compressed):

首先,获取文件的所有行(以下代码可以压缩):

$file = @fopen($dir, 'r'); # As you said, $dir is your filename
if ($file) { # Ending bracket is at the end
    if (filesize($dir)) { # Checks whether the file size is not zero (we know file exists)
        $fileContent = fread($file, filesize($dir)); # Reads all of the file
        fclose($file);
    } else {
        // File is empty
        exit; # Stops the execution (also you can throw an exception)
    }
    $fileLineByLine = explode(PHP_EOL, $fileContent); # Divides the file line by line

Here, you can perform your search:

在这里,您可以执行搜索:

    $key = false; # By default, your string $line is not in the file (false)
    foreach ($fileLineByLine as $lineNumber => $thisLine)
        if ($thisLine === $line)
            $key = $lineNumber; # If $line found in file, set $key to this line number

Simply, you can remove line $key + 1:

简单地说,您可以删除行 $key + 1:

    if ($key !== false) # If string $line found in the file
        unset($fileLineByLine[$key]); # Remove line $key + 1 (e.g. $key = 2, line 3)

At last, you must save your changes to the file:

最后,您必须将更改保存到文件中:

    $newFileContent = implode(PHP_EOL, $fileLineByLine); # Joins the lines together
    $file = fopen($dir, "w"); # Clears the file
    if ($file) {
        fwrite($file, $newFileContent); # Saves new content
        fclose($file);
    }
} # Ends 'if ($file) {' above

Also you can set above code as a function.

您也可以将上面的代码设置为函数。

Notes:

笔记:

  • $line must not have new line characters like \n. You must remove them:

    $line = str_replace(PHP_EOL, '', $line);
    
  • Don't use

    $fileLineByLine[$key] = "";
    

    instead of

    unset($fileLineByLine[$key]);
    

    because the first case doesn't remove the line, it just clears the line (and an unwanted empty line will remain). In that case, implode() adds a new line also for $fileLineByLine[$key] which is empty; otherwise if you unset a variable, it will unavailable (and implode() can not find it).

  • $line 不能有像 \n 这样的换行符。您必须删除它们:

    $line = str_replace(PHP_EOL, '', $line);
    
  • 不要使用

    $fileLineByLine[$key] = "";
    

    代替

    unset($fileLineByLine[$key]);
    

    因为第一种情况不会删除该行,它只是清除该行(并且会保留不需要的空行)。在这种情况下,implode() 也会为空的 $fileLineByLine[$key] 添加一个新行;否则,如果您取消设置一个变量,它将不可用(并且 implode() 找不到它)。

回答by Vitalicus

Convert text to array, remove first line and reconvert to text

将文本转换为数组,删除第一行并重新转换为文本

$line=explode("\r\n",$text);
unset($line[0]);
$text=implode("\r\n",$line);

回答by super

Like this:

像这样:

file_put_contents($filename, str_replace($line . "\r\n", "", file_get_contents($filename)));