2013-03-14 118 views
0

我有一個文本文件(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); 

回答

2

我能想出的

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

您已打開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

-1
$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"); 
0

它的工作對我來說

<?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