简体   繁体   English

使用php删除文件中包含特定单词的行之前的所有行

[英]Delete all lines before a line that included specific word in a file by using php

I need a simple code in php that can delete all lines before a line that included a specific word, for example this is contents of foo.txt: 我需要php中的简单代码,可以删除包含特定单词的行之前的所有行,例如,这是foo.txt的内容:

.

.

eroigjeoj

dvjdofgj

dsfdsft

reytyjkjm

.

.

[DATA]

1,2,4

3,4,5

.

.

.

I want to delete all lines before line that included "[DATA]" and delete that line too. 我想删除包含“ [DATA]”的行之前的所有行,也删除该行。 and the result be a foo.txt with this content: 结果是具有以下内容的foo.txt:

1,2,4

3,4,5

.

.

.

Here is one approach, maybe not the most efficient. 这是一种方法,可能不是最有效的。

  • Create a new text file (text2). 创建一个新的文本文件(text2)。

     $text2 = fopen("text2", "w"); 
  • Initialise a boolean value to false. 将布尔值初始化为false。

     $hitWord = false; 
  • Read through original text file (text1) line by line until you hit the String '[DATA]', adding the subsequent lines to text2 逐行阅读原始文本文件(text1),直到您击中字符串'[DATA]',然后将后续各行添加到text2

     $handle = fopen("text1.txt", "r"); if ($handle) { while (($line = fgets($handle)) !== false) { if($hitWord){ fwrite($text2, $line . "\\n"); }else{ if(strpos($line,'[DATA]') !== false){ $hitWord = true; } } } fclose($handle); } else { // error opening the file. } 
  • Delete text1 using unlink($text1) // you will need path 使用unlink($text1)删除text1 //您将需要路径

  • Rename text2 to text1 using rename() function. 使用rename()函数将text2重命名为text1。

ALTERNATIVELY 交替地

You could use the same approach above. 您可以使用上面的相同方法。 Except instead of editing a new text file, edit a new String and just replace all the lines in text1 with this string at the end of the program. 除了代替编辑新的文本文件外,还可以编辑新的String并在程序末尾仅用此字符串替换text1所有行。

This would save you having to create/delete/edit new files. 这样可以省去创建/删除/编辑新文件的麻烦。 Make sure new line is used correctly 确保正确使用新行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM