Remove comment lines from TXT files

6

I would like to know how to remove comment tags from TXT files with PHP , could anyone help me?

I'm having this problem reading txt files that are displaying the 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);  

File txt:

//TEST
//TEST
'test'    1   1   1   1   1   1   1
    
asked by anonymous 03.01.2018 / 16:49

1 answer

7

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

$linhas = file($arquivo, FILE_IGNORE_NEW_LINES);

Manual:

  

link

Then just remove the unwanted lines:

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

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

Manual:

  

link

  

link

Now, if you only want to view or save, you do not even need to array_filter , just do this:

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 to pieces, and go recording without retaining everything in memory. I did not go into detail for not being applicable to most cases, but it's good to keep that in mind.

Basically, it is a question of changing the file by reading line by line, and use a if + substr according to the last example

    
03.01.2018 / 17:23