Jump to content
Marcos RJ

Retirar espaços de um arquivo txt com PHP

Recommended Posts

Olá pessoal.

 

Como faço para retirar os espaços de um arquivo txt? Por ex.: Tenho o arquivo abaixo (apenas um trecho, pois o arquivo é grande):

 

10400000         2090183800001990000000000000000000001234204321000000000EMPRESA                       C ECON FEDERAL                          20601201405551100162204000000                    RETORNO-PRODUCAO                  000            
10400011T0100030 20090183800001990000000000000000000001234204321000000000EMPRESA                                                                                                       00001622060120140000000000                          00   
1040001300001T 060000000432100000000   240000000111369979100000000000000002012014000000000008000000010860000000000000000          090000000000000000     

Como faço para que ele fique da seguinte forma (O ex. abaixo é de um outro arquivo):

 

02RETORNO0000000000000000011119999990000000000000000000000000000000000000000104000000000000000201016000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001

O código inicial que tenho é esse:

$arquivo = $_FILES["Arquivo"]["tmp_name"];

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

while(!feof($ler)){

   $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>";

Obrigado

Share this post


Link to post
Share on other sites
13 minutos atrás, washalbano disse:

Olá!
Use preg_replace:
preg_replace('/\s+/', '', $string);
onde $string é o texto de onde o sr. pretende remover os espaços em branco.
http://php.net/manual/pt_BR/function.preg-replace.php

 

Olá washalbano.

 

Certo. Coloco o preg_replace depois do while() e coloco a variável $ler? Porque quando coloco antes, ele fica lendo e não responde.

 

 

Share this post


Link to post
Share on other sites
58 minutos atrás, washalbano disse:

Olá!
Use preg_replace:
preg_replace('/\s+/', '', $string);
onde $string é o texto de onde o sr. pretende remover os espaços em branco.
http://php.net/manual/pt_BR/function.preg-replace.php

 

Olá washalbano.

 

Certo. Coloco o preg_replace depois do while() e coloco a variável $ler? Tentei dessa forma, mas a página fica lendo e não retorna nenhum resultado:

 

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

 

 

Share this post


Link to post
Share on other sites

Fiz uma alteração no meu código. Coloquei:

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

foreach($arquivo as $linhasNum => $linhas) {

              $testes = substr($arquivo[$linhasNum],3,5);

}
echo $testes; // Retorno: Testes: 99999 ( retorna do último array 21 e não do primeiro )

Parece que consegui tirar os espaços, porém quando dou um print_r() na variável $arquivo, ele retorna:

 

Array ( [0] => 104000002090183800001990000000000000000000001234204321000000000EMPRESACECONFEDERAL20601201405551100162204000000RETORNO-PRODUCAO000 [1] => 10400011T010003020090183800001990000000000000000000001234204321000000000EMPRESA0000162206012014000000000000 [2] => 1040001300001T060000000432100000000240000000111369979100000000000000002012014000000000008000000010860000000000000000090000000000000000000000000000125020101 [3] => 1040001300002U06000000000000000000000000000000000000000000000000000000000000000000000008000000000000008000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [4] => 1040001300003T060000000432100000000240000000111381979100000000000000005012014000000000008000000033170000000000000000090000000000000000000000000000125020101 [5] => 1040001300004U06000000000000000000000000000000000000000000000000000000000000000000000008000000000000008000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [6] => 1040001300005T060000000432100000000240000000111378897100000000000000010012014000000000008000000011920000000000000000090000000000000000000000000000125020101 [7] => 1040001300006U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [8] => 1040001300007T060000000432100000000240000000111371256100000000000000010012014000000000008000000011920000000000000000090000000000000000000000000000125020101 [9] => 1040001300008U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [10] => 1040001300009T060000000432100000000240000000000222473100000000000000015012014000000000008000000002700000000000000000090000000000000000000000000000125020101 [11] => 1040001300010U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [12] => 1040001300011T060000000432100000000240000000111369162100000000000000010012014000000000008000000031280000000000000000090000000000000000000000000000125020101 [13] => 1040001300012U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [14] => 1040001300013T060000000432100000000240000000111368980100000000000000010012014000000000008000000036620000000000000000090000000000000000000000000000125020101 [15] => 1040001300014U06000000000000000000000000000000000000000000000000000000000000000000000008000000000000008000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [16] => 1040001300015T060000000432100000000240000000000319990100000000000000010012014000000000048000000011920000000000000000090000000000000000000000000000125020101 [17] => 1040001300016U06000000000000000000000000006000000000000000000000000000000000000000000042000000000000042000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [18] => 1040001300017T060000000432100000000240000000000305727100000000000000010012014000000000008000237017950000000000000000090000000000000000000000000000270040101 [19] => 1040001300018U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [20] => 1040001500002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 [21] => 10499999000001000022 )

E quando dou o print_r() na variável $arquivo[$linhasNum], o retorno é esse:

 

104000002090183800001990000000000000000000001234204321000000000EMPRESACECONFEDERAL20601201405551100162204000000RETORNO-PRODUCAO000
10400011T010003020090183800001990000000000000000000001234204321000000000EMPRESA0000162206012014000000000000
1040001300001T060000000432100000000240000000111369979100000000000000002012014000000000008000000010860000000000000000090000000000000000000000000000125020101
1040001300002U06000000000000000000000000000000000000000000000000000000000000000000000008000000000000008000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001300003T060000000432100000000240000000111381979100000000000000005012014000000000008000000033170000000000000000090000000000000000000000000000125020101
1040001300004U06000000000000000000000000000000000000000000000000000000000000000000000008000000000000008000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001300005T060000000432100000000240000000111378897100000000000000010012014000000000008000000011920000000000000000090000000000000000000000000000125020101
1040001300006U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001300007T060000000432100000000240000000111371256100000000000000010012014000000000008000000011920000000000000000090000000000000000000000000000125020101
1040001300008U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001300009T060000000432100000000240000000000222473100000000000000015012014000000000008000000002700000000000000000090000000000000000000000000000125020101
1040001300010U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001300011T060000000432100000000240000000111369162100000000000000010012014000000000008000000031280000000000000000090000000000000000000000000000125020101
1040001300012U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001300013T060000000432100000000240000000111368980100000000000000010012014000000000008000000036620000000000000000090000000000000000000000000000125020101
1040001300014U06000000000000000000000000000000000000000000000000000000000000000000000008000000000000008000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001300015T060000000432100000000240000000000319990100000000000000010012014000000000048000000011920000000000000000090000000000000000000000000000125020101
1040001300016U06000000000000000000000000006000000000000000000000000000000000000000000042000000000000042000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001300017T060000000432100000000240000000000305727100000000000000010012014000000000008000237017950000000000000000090000000000000000000000000000270040101
1040001300018U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001500002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
10499999000001000022

 

Share this post


Link to post
Share on other sites

Olá!

Use o preg_replace dentro do foreach

Na variável $linha

Aparentemente a variável  $arquivo é do tipo array

E pra remover espaços em branco, o preg_replace espera uma variável do tipo string

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • By Leandro Volanick
      Boa tarde pessoal.
       
      Gostaria de uma ajuda em uma consulta sql, onde quero agrupar os todos produtos comprados pelo mesmo CPF, dentro de uma array. 
       
      Segue o que estou usando:
      $data=mysqli_query($mysqli, "SELECT xml.id, xml.xProd as produto, prod.id as iddoproduto, GROUP_CONCAT( prod.xProd ) FROM produtos AS prod LEFT JOIN xml as xml ON xml.xProd = prod.xProd GROUP BY xml.CPFdest"); while($info=mysqli_fetch_array($data)) echo '['.$info['iddoproduto'].'],'; No momento, o codigo está trazendo apenas 1 produto, quero que ele printe todos produtos que o CPFdest já comprou.
       
       
    • By Vítor Gonçalves
      Boa Tarde, gostaria se alguém poderia me ajudar!
      tenho um sistema desktop que é validado a cada 6 meses, quando termina essa validade ele pedi para renovar!
      - desejo criar um script em PHP  com a seguinte função:
      -pegar a senha gerada no sistema e enviar para o servidor web( hostinger server-sql) via php
      - o servidor gera e mostra uma contra senha  para ser copiada de volta.
      - ao colar a contra senha no campo "nova licença" no meu programa, ele compara com a que tá no banco de dados na hostinger se bate a mesma e libera o uso.
       
      - já vi isso em outro sistema mas não tive acesso aos scripts para ver como funciona.
    • By Anonicah
      Olá preciso de ajuda com esse exercício. Montei até a parte de formulário + validação de javascrip no dreamweaver mas buguei com o resto. O que eu fiz:
       

      <html>
      <head>
      <title> Formulário CPF validado com Java Script </title>
          
          <script language="javascript" type="text/javascript">
      function validar() {
      var cpf = form1.cpf.value;
          
      if (cpf == "") {
      alert('Preencha o campo com seu cpf');
      form1.cpf.focus();
      return false;
      }
          
      }
      </script>
          
          
      </head>
      <body>
      <form name="form1" action="enviar.php" method="post">
      CPF:
      <input name="cpf" type="text"><br /><br />
      <input type="submit"  onclick="return validar()">
      </form>
      </body>
      </html>
       
       
      EXERCÍCIO
      Criar um formulário simples em html com um único campo CPF;
      Fazer uma validação em javascript antes de fazer o post;
      Consumir o WS https://bi.vidaclass.com.br/utils para consultar informações do CPF enviado pelo form;
      Do retorno obtido exibir na tela:
      Nome, email, telefone
      Se tem compra em saude: Sim | Não
      Quantas compras: (5) ex.
      Se tem farma: Sim | Não
      Se tem dependente: Sim | Não
      Qtd. de dependentes: (2) ex.

      Obtem o token para consumir os endpoints;
      https://bi.vidaclass.com.br/auth
      {
          "company_id": 1,
          "username": "webmaster@vidaclass.com.br",
          "password": "Teste20170705"
      }
      Endpoint para consultar o CPF
      https://bi.vidaclass.com.br/utils
      {
          "action": 4,
          "key": {
              "cpf": 25383193820
          }
      }
    • By Luciano Marques
      Então pessoal é o seguinte: Estou tendo problemas para impedir acesso simultâneo no meu projeto. Foi depois de muito pesquisar que vim aqui abrir esse tópico. 
      Enfim, eu até consegui colocar uma teoria em prática que era a de criar uma coluna na tabela `usuarios` com 1 para ativo, e 2 para  inativo. e depois coloquei no topo a condição IF para se 1 já preenchido não permite o login. até ai de boa. o problema vem se o usuário não desloga só fecha a janela. a coluna ainda permanece como ativa 1. mesmo expirando o login, não ocorre o update na base de dados. Se alguém puder me ajudar nessa, preciso concluir esse trabalho ainda essa semana. desde já agradeço 
    • By paulojk
      Como faço essa funçao alguem sabe? Depos que o usuario clica no botao so libera depois de um determinado tempo.
       


×

Important Information

Ao usar o fórum, você concorda com nossos Terms of Use.