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 EvertonFD
      Olá alguém pode me ajudar?
      estou tentando pegar valores do check box selecionado e por no banco de dados a questão é que:
      Quando eu faço uma seleção vai de boa quando seleciono mais de uma fica tudo em branco.
      estou usando esse codigo:
      <?php if(isset($_POST['submit'])){ if(!empty($_POST['checkArr'])){ foreach($_POST['checkArr'] as $checked){ echo $checked . '<br>'; } } else { echo '<div class="error">Checkbox is not selected!</div>'; } } ?> <div class=" form-row"> <div class="col-md-4 text-left"> <div class="form-check col-md-12"> <input class="form-check-input" type="checkbox" name="checkArr[]" value="Iluminação Publica"> <label class="form-check-label" for="gridCheck"> Iluminação Publica </label> </div> <div class="form-check col-md-12"> <input class="form-check-input" type="checkbox" name="checkArr[]" value="Saneamento Basíco"> <label class="form-check-label" for="gridCheck"> Saneamento Basíco </label> </div> <div class="form-check col-md-12"> <input class="form-check-input" type="checkbox" name="checkArr[]" value="Alamentos"> <label class="form-check-label" for="gridCheck"> Alagamentos </label> </div> //que vai para o insert: <?php session_start(); include_once("../conexao.php"); $nome = filter_input(INPUT_POST, 'nome', FILTER_SANITIZE_STRING); $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL); $tel = filter_input(INPUT_POST, 'telefone', FILTER_SANITIZE_STRING); $bairro = filter_input(INPUT_POST, 'bairro', FILTER_SANITIZE_STRING); $end = filter_input(INPUT_POST, 'end', FILTER_SANITIZE_STRING); //--------------------------------- $problema = filter_input(INPUT_POST, 'checkArr[]', FILTER_SANITIZE_STRING); $observacao = filter_input(INPUT_POST, 'observacao', FILTER_SANITIZE_STRING); //--------------------------------- //$resposta = filter_input(INPUT_POST, 'resposta', FILTER_SANITIZE_STRING); $result_usuario = "INSERT INTO itaim ( nome, email, telefone, bairro, rua_cep, problemas, detalhes, created) VALUES ('$nome', '$email' , '$tel' , '$bairro' , '$end' , '$problema' , '$observacao' , NOW())"; $resultado_usuario = mysqli_query($conn, $result_usuario); if(mysqli_insert_id($conn)){ $_SESSION['msg'] = "<p style='color:green;'>Menssagem envida</p>"; header("Location: ../index.php"); }else{ header("Location: ../index.php"); //$_SESSION['msg'] = "<p style='color:red;'>Houve um errono envio favor informar.</p>"; } Quem puder me ajudar agradeço muito
       
    • By juliosertori
      Amigos, estou utilizando um sistema de FormValidation, e vem pronta algumas coisas, mas estou com dúvida:
       
      Como pego os dados desse POST no PHP?
       
      FormValidation.utils.fetch(formSubmitUrl, { method: 'POST', dataType: 'json', params: { name: form.querySelector('[name="username"]').value, email: form.querySelector('[name="password"]').value, }, }) Obrigado!
    • By msergioaguiar
      boa noite a todos

      hoje um cliente me procurou querendo um sistema.
      ele Trabalha com aposta esportiva ele quer um sistema q quando ele fazer a aposta na conta dele esta aposta seja feita em varios outros usuarios q esta logados em pcs na intarnet.

      Gostaria de uma ajuda como vou fazer isso mais gostei muito do projeto

      desde ja fico muito grato a todos pela ajuda
    • By Usleydocarmo
      Estou com o seguinte erro:
      Ao acessar o meu site na pagina principal tudo ok. Porém quando acesso em um menu que vai carregar um arquivo que está em uma pasta e não na pasta raiz, ai o arquivo css não é carregado.
       
      <a href="usuarios"> home</a> chamo o arquivo funcionarios na mesma pasta onde está o arquivo index.php -funciona
      <a href="usuarios/usuarios"> home</a>  Pasta 'usuarios' e dentro dela chamo o arquivo 'usuarios' - ai não funciona
       
      Descobri que quando entro na pasta usuários fica assim, com a basta no diretório do arquivo. Como corrigir?
      <link rel="stylesheet" href="http://localhost/keiri/admin/usuarios/plugins/fontawesome-free/css/all.min.css&nbsp;">
       
      Meu htaccess
      RewriteRule ^([a-z]+)\/?$ dashboard.php?arquivo=$1 [NC,L]
      RewriteRule ^([a-z]+)\/([a-z]+)$ dashboard.php?pasta=$1&arquivo=$2 [NC,L]
      RewriteRule ^([a-z]+)\/([a-z]+)\/([0-9]+)$ dashboard.php?pasta=$1&arquivo=$2&item=$3 [NC,L]
    • By msantino
      Bom dia.
       
      Estou desenvolvendo uma aplicação que vai acessar e gravar dados via webservice dentro do nosso crm... mas estou com um problema que quando tento fazer o acesso mostra a seguinte mensagem de erro:
       
      Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing Schema: can't import schema from 'http://dsksp015.phonoway.com.br:8051/wsDataServer/mex?xsd=xsd0' in /home/httpd/html/phonoweb.com.br/public_html/carrinhobitrix_busca/teste_soap.php:113 Stack trace: #0 /home/httpd/html/phonoweb.com.br/public_html/carrinhobitrix_busca/teste_soap.php(113): SoapClient->SoapClient('http://187.93.2...') #1 {main} thrown in /home/httpd/html/phonoweb.com.br/public_html/carrinhobitrix_busca/teste_soap.php on line 113
       
      Não sei se faz alguma diferença, mas nosso CRM é o TOTVS RM
       
      Grato.
×

Important Information

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