Removing a part of the text inside a txt file

Asked

Viewed 880 times

3

Colleagues.

I have the following code where I pick up a csv file by uploading and storing it in a txt file, which has to have the formation of positions according to the database of a program. For this I am using the code below:

         $diretorio = 'arquivos/';
            $arquivo = $diretorio . basename($_FILES['userfile']['name']);

            if (move_uploaded_file($_FILES['userfile']['tmp_name'], $arquivo)){

               $abrirArquivo = fopen($arquivo, "r");

              while(!feof($abrirArquivo)) {
                    $ler = fgets($abrirArquivo,460);
                    $campo1 = substr($ler, 0, 8);
                    $campo2 = substr($ler, 9,10);
                    $campo3 = substr($ler, 20, 10);
                    $campo4 = substr($ler, 31, 22);
                    $campo5 = substr($ler, 40, 10);

$leituraFinal = "
$campo1          $campo2   $campo3                          $campo4                     $campo5<br>";

                //$trocar = str_replace("<br>","",$leituraFinal);
                $trocar = preg_replace("<br>",null,$leituraFinal);
                file_put_contents($diretorio . "JAN_2012.txt",$leituraFinal,FILE_APPEND);
                file_get_contents($diretorio . "JAN_2012.txt");

            }
     }
}

Cool. Works, at least in parts, because in the txt file appears at the end of the line the < br >.

2 answers

4


If I understand correctly you want to replace "null" with a newline in the txt file. I believe that for that you have to do the following:

$trocar = preg_replace("\n", null, $leituraFinal);

Replacing the previous code:

$trocar = preg_replace("<br>",null,$leituraFinal);

0

So you can remove the tag br of the final txt file, you could do as follows by changing the following code code:

$trocar = preg_replace("<br>",null,$leituraFinal);

To:

$trocar = preg_replace('/<br>$/', '', $leituraFinal);

Where regular expression will only remove the br that is at the end of txt, but in case you want to remove all br that may exist in this txt file do so:

$trocar = preg_replace('/<br>/', '', $leituraFinal);

Browser other questions tagged

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