Ali
Ali

Reputation: 632

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:

.

.

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. and the result be a foo.txt with this content:

1,2,4

3,4,5

.

.

.

Upvotes: 0

Views: 372

Answers (1)

user5132172
user5132172

Reputation:

Here is one approach, maybe not the most efficient.

  • Create a new text file (text2).

    $text2 = fopen("text2", "w");
    
  • Initialise a boolean value to false.

    $hitWord = false;
    
  • Read through original text file (text1) line by line until you hit the String '[DATA]', adding the subsequent lines to 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

  • Rename text2 to text1 using rename() function.

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.

This would save you having to create/delete/edit new files. Make sure new line is used correctly

Upvotes: 1

Related Questions