0

How do I remove spaces from a text file? I tried the code below but I could not:

The file

10400000         2090183800001990000000000000000000001234204321000000000EMPRESA                       C ECON FEDERAL                          20601201405551100162204000000                    RETORNO-PRODUCAO                  000            
10400011T0100030 20090183800001990000000000000000000001234204321000000000EMPRESA                                                                                                       00001622060120140000000000 

How the file has to stay:

02RETORNO0000000000000000011119999990000000000000000000000000000000000000000104000000000000000201016000000000

The code

 $arquivo = fopen($_FILES["Arquivo"]["tmp_name"], "r");
$arquivo = preg_replace('/\s+/', '', $arquivo);

while (!feof($arquivo)) {
  $linhas = fread($ler,999999);
  $banco = substr($linhas,0,3);
  $lote = substr($linhas,4,7);
  $registro = substr($linhas,8,8);
}
echo "Banco: " .$banco. "<br>";
echo "Lote: " .$lote. "<br>";
echo "Registro: " .$registro. "<br>";
  • Possible duplicate of https://stackoverflow.com/questions/2109325/how-to-strip-all-spaces-out-of-a-string-in-php – MichaelK May 19 '18 at 19:36
  • Your code is not changing the file at all, it only reads from it. If you want something to be removed from the file, then you should at least write to it. – trincot May 19 '18 at 19:39
  • Right. I changed my post. –  May 19 '18 at 19:41
  • I tried using the code: `$arquivo = preg_replace ('/\s+/', '', $arquivo);` Before the while () but when I run, it keeps reading and crashes the browser. –  May 19 '18 at 19:46
  • The change you've made is nonsensical. `preg_replace` works on strings, but `$arquivo` is a file handle. And you still aren't writing anything anywhere. – Greg Schmidt May 19 '18 at 20:00
  • Read the file, store the contents in a variable, remove the spaces using `preg_replace` or `str_replace` and rewrite the file? – rpm192 May 19 '18 at 20:22

1 Answers1

0

have you tried using file_get_contents ?

try this..

$ar = $_FILES["Arquivo"]["tmp_name"];
$arquivo = file_get_contents($ar);
$arquivo = preg_replace('/\s+/', '', $arquivo);