如何从文件中删除包含某些文本的所有行以及紧随其后的行

时间:2019-05-13 20:50:53

标签: php

我的php不再那么好了。 我知道这很简单,但是我迷失了在解决方案中发现的代码。

我需要修改文件以删除一些行:当匹配一行中的字符串时,我需要删除该行以及该行之后的行。

  /*$file already received via curl*/  
  file_put_contents("orig", $file);  

  /*missing part removing the lines*/
  $file ... remove lines containing "STRING" and the line following those  

  /*do some other manipulation*/
  $file = str_replace("aa","bb",$file);
  $file = str_replace("cc","dd",$file);

  /*preparing the file*/
  $output = "modified";
  file_put_contents($output, $file);

  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-stream');
  header('Content-Length: '.filesize($output));

  /*returning the file*/
  readfile($output);
  exit;

例如在文件中

1  gooo aaaaaaaaaaa
2  ----------------
3  jlfjsdfjjfas
4  lkflkdsafòklaf
5  gooo ljlkjlklkjl
6  jlfkjsdlkfjlskdjflksd
7  òfnsdòafdnòaf 
8  flksjflksdajfòalk

搜索“ gooo”,输出文件将包含第3 4 7 8行

3  jlfjsdfjjfas
4  lkflkdsafòklaf
7  òfnsdòafdnòaf 
8  flksjflksdajfòalk

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

这应该可以解决问题。最好使用fgetsfputs逐行读取和写入文件,而不是将整个输入文件加载到内存中,并且本质上在内存中创建一个副本,减去几行。

<?php
//Path to input file
$inFilePath = 'test.txt';

//Path to output file
$outFilePath = 'test_out.txt';

//Create file handles for our input and output files
$inHandle = fopen($inFilePath, 'r');
$outHandle = fopen($outFilePath, 'w');

//Define the search string
$searchTerm = 'gooo';

//Keep count of bytes written (it's a freebie) so we don't need to call filesize
$outFileSize = 0;

//If we have a good handle, do the business
if ($inHandle)
{
    //Define a flag to keep track of whether or not to skip the next line
    $skipNext = false;

    /*
     * Read our file one line at a time, so we don't pull the whole thing into memory
     */ 
    while (($currLine = fgets($inHandle)) !== false)
    {
        if($skipNext)
        {
            //If we're skipping this line, reset the skip flag and move to the next iteration
            $skipNext = false;
            continue;
        }

        //Search for the string, and if we find it, set the skip flag and move to the next iteration
        if(strpos($currLine, $searchTerm)!==false)
        {
            $skipNext = true;
            continue;
        }

        //If we're here, we have a valid line. Write it to the out file and update our byte count
        $outFileSize += fputs($outHandle, $currLine);
    }

    //Close our handles
    fclose($inHandle);
    fclose($outHandle);
}

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Length: '.$outFileSize);

/*returning the file*/
readfile($outFilePath);
exit;