【问题标题】:Remove a line from file if it exists从文件中删除一行(如果存在)
【发布时间】:2017-05-18 19:45:11
【问题描述】:

我已经习惯了 PHP,并尝试从文件中删除一行(如果存在)并重新保存文件。

如果我有文件

user1
user2
user3
user4

我可以使用

if(existsAndRemove("user3")){
    do thing
}

我尝试使用类似于以下代码的代码,但它有时会出错,并且只会删除文件中最后一行的行。我不知道如何解决这个问题。

$data2 = file("./ats.txt");
 $out2 = array();
 foreach($data2 as $line2) {
     if(trim($line2) != $acc) {
         $out2[] = $line2;
     }
 }
 $fp2 = fopen("./ats.txt", "w+");
 flock($fp2, LOCK_EX);
 foreach($out2 as $line2) {
     fwrite($fp2, $line2);
 }
 flock($fp2, LOCK_UN);
 fclose($fp2);  
  }
}    

任何帮助都将不胜感激,如果您也能解释代码,我也将不胜感激,这样我就可以更容易地从中学习!! 谢谢。

【问题讨论】:

  • 覆盖打开的文件还是另存为新文件?
  • 看起来你还没有定义$acc$acc = "user3";
  • @Arbels 覆盖文件,抱歉。
  • @cmorrissey 它已经在上面定义了我只是没有包含它

标签: php file io


【解决方案1】:

如果文件足够小,您不必担心将其全部读入内存,您可以做一些更实用的事情

// Read entire file in as array of strings
$data = file("./ats.txt");

// Some text we want to remove
$acc = 'user3';

// Filter out any lines that match $acc, 
// ignoring any leading or trailing whitespace
//
$filtered_data = array_filter(
    $data, 
    function ($line) use ($acc) {
        return trim($line) !== $acc;
    }
)

// If something changed, write the file back out
if ($filtered_data !== $data) {
    file_put_contents('./ats.txt', implode('', $filtered_data));
}

【讨论】:

    【解决方案2】:

    这样的事情可能会奏效:

    function remove_user($user) {
        $file_path = "foo.txt"
        $users = preg_split("[\n\r]+", file_get_contents($file_path));
        foreach ($users as $i => $existing) {
            if ($user == $existing) {
                $users = array_splice($users, $i, 1);
                file_put_contents($file_path, implode("\n", $users));
                break;
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      应该会容易得多,因为您已经在使用file()

      $data2 = file("./ats.txt", FILE_IGNORE_NEW_LINES);
      unset($data2[array_search('user3', $data2)]);
      file_put_contents("./ats.txt", implode("\n", $data2));
      

      或者先检查是否存在:

      $data2 = file("./ats.txt", FILE_IGNORE_NEW_LINES);
      
      if( ($key = array_search('user3', $data2)) !== false ) {
          unset($data2[$key]);
          file_put_contents("./ats.txt", implode("\n", $data2));
      }
      

      【讨论】:

        猜你喜欢
        • 2015-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-14
        • 1970-01-01
        • 1970-01-01
        • 2021-07-12
        • 2021-08-07
        相关资源
        最近更新 更多