1

複数行にテキストがあるテキストファイル(in.txt)があります。変数文字列を検索し、見つかった場合はその行全体を削除する必要がありますが、他の行は保持します。以下のスクリプトを使用しましたが、すべてのデータが削除され、検索したものが書き込まれているようです。誰かが私を正しい方向に向けることができますか?「key」は私が検索している文字列です。

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

4 に答える 4

4

私が思いつくことができる最も簡単なのは

<?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);
于 2013-03-14T10:03:41.350 に答える
1

ファイルをwriteモードで開きました。これにより、すべてのデータが削除されます。

新しいファイルを作成する必要があります。新しいものにデータを書き込みます。古いものを削除します。そして、新しい名前に変更します。

OR

このファイルをreadモードで開きます。このファイルのデータを変数にコピーします。モードで再度開きwriteます。そして、データを書き込みます。

于 2013-03-14T09:54:54.650 に答える
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);
 ?>
于 2013-03-14T10:26:28.040 に答える
-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");
于 2013-03-14T10:00:41.230 に答える