php文本文件搜索和删除

问题描述:

我有一个文本文件(in.txt),它有多行文本。我需要搜索一个变量字符串,如果找到了,则删除整行,但保留其他字符串。我已经使用了下面的脚本,但它似乎摆脱了所有数据并写下了我正在寻找的内容。请有人指出我正确的方向? 'key'是我正在搜索的字符串。php文本文件搜索和删除

$key = $_REQUEST['key']; 
$fc=file("in.txt"); 


$f=fopen("in.txt","w"); 


foreach($fc as $line) 
{ 
     if (!strstr($line,$key)) 
     fputs($f,$line); 
} 
fclose($f); 

我能想出的

<?php 

    $key = 'a'; 
    $filename = 'story.txt'; 
    $lines = file($filename); // reads a file into a array with the lines 
    $output = ''; 

    foreach ($lines as $line) { 
     if (!strstr($line, $key)) { 
      $output .= $line; 
     } 
    } 

    // replace the contents of the file with the output 
    file_put_contents($filename, $output); 

您已打开write模式的文件。这将删除其所有数据。

您应该创建一个新文件。将数据写入新的数据。删除旧的。并重新命名一个新的。

OR

打开此文件中read模式。将该文件的数据复制到变量中。再次打开write模式。并写入数据。

+0

好感谢,但有没有一个更简单的方法最简单?我不知道如何去做你的建议。 – Martyn 2013-03-14 09:56:19

+0

@ user1592162 - 请参阅更新。 – 2013-03-14 09:57:04

+0

我何时删除该行?在写入文件时写入 – Martyn 2013-03-14 10:01:07

$key = $_REQUEST['key']; 
$fc=file("in.txt"); 


$f=fopen("in_temp.txt","w"); 

$temp = array(); 
foreach($fc as $line) 
{ 
    if (substr($line,$key) === false) 
     fwrite($f, line); 
} 
fclose($f); 
unlink("in.txt"); 
rename("in_temp.txt", "in.txt"); 

它的工作对我来说

<?php 
$key = $_REQUEST['key']; 
$contents = ''; 
$fc=file("in.txt"); 
foreach($fc as $line) 
    { 
    if (!strstr($line,$key)) 
    { 
     $contents .= $line; 
    } 
    } 
    file_put_contents('in.txt',$contents); 
?> 
+0

它带有$内容作为未定义的变量。我无法弄清楚我是如何分类的。干杯。 – Martyn 2013-03-14 14:06:09

+0

@ user1592162嘿看到我编辑的帖子,它应该可以帮助你..并在运行此脚本后检查in.txt – alwaysLearn 2013-03-14 15:02:56