Php 从文件中删除行(如果存在)

Php 从文件中删除行(如果存在),php,file,io,Php,File,Io,我已经习惯了PHP,尝试从文件中删除一行(如果存在)并重新保存该文件 所以如果我有文件 user1 user2 user3 user4 我可以用 if(existsAndRemove("user3")){ do thing } 我曾尝试使用类似于下面代码的代码,但有时会出现错误,只有在文件中最后一行时才会删除该行。我不知道如何解决这个问题 $data2 = file("./ats.txt"); $out2 = array(); foreach($data2 as $line2)

我已经习惯了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);  
  }
}    
任何帮助都将不胜感激,如果您也能解释代码,我也将不胜感激,这样我可以更容易地从中学习!!
谢谢。

类似的方法可能会奏效:

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

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

或者先检查它是否存在:

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

如果文件大小足够小,您不必担心将其全部读入内存,那么您可以做一些功能更强大的事情

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

覆盖打开的文件或另存为新文件?看起来您没有定义
$acc
ie
$acc=“user3”@Arbels正在覆盖该文件,很抱歉。@cmorrissey上面已经定义了它,我只是未能包含它
// 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));
}