Remove comment lines from TXT files

Asked

Viewed 218 times

6

I wonder how to remove comment tags from files TXT with PHP, someone could help me?

I’m having this problem in reading txt files that are displaying comments.

PHP code:

function extrairDadosNotificacao($NomeArquivo){
      $arquivo = fopen($NomeArquivo, 'r');

      $dados = array();
      while (($buffer = fgets($arquivo, 4096)) !== false) {
          $dados[] = $buffer;
      }
      return $dados;
}

$test = extrairDadosNotificacao("test.txt");


echo "<pre>";
var_dump($test);  

txt file :

//TEST
//TEST
'test'    1   1   1   1   1   1   1
  • 1

    I changed, in case I wanted to know how to remove the /TEST comments

1 answer

7


First of all, you can read the file on array in this way:

$linhas = file($arquivo, FILE_IGNORE_NEW_LINES);

Handbook:

http://php.net/manual/en/function.file.php

Then just remove the unwanted lines:

function naoecomentario($val){
    return '//' != substr($val, 0, 2);
}
$linhasfiltradas = array_filter($linhas, 'naoecomentario');

From there you can save on disk line by line, or join with implode.

Handbook:

http://php.net/manual/en/function.substr.php

http://php.net/manual/en/function.array-filter.php

Now, if it’s just show or save, you don’t even need array_filter, that’s all it takes:

foreach($linhasfiltradas as $linha) {
    if('//' != substr($val, 0, 2)) {
       // ... mostra na tela ou salva no arquivo ...
       echo htmlentities($linha)."<br>\n";
    }
}


Important: If the file is too large, it may be the case to read the pieces, and record without retaining everything in memory. I didn’t go into detail because it’s not applicable to most cases, but it’s nice to keep that in mind.

Basically it’s about changing the file by reading line by line, and use to a if + substr as the last example

Browser other questions tagged

You are not signed in. Login or sign up in order to post.