insert commas into.txt file alignments

Asked

Viewed 75 times

0

I wonder how do I insert commas into txt file., for example

000000005200040630161811301230
000000006200052200050001000200
000000007200061318223617001730

to look like this:

000000005,2000406,301618113012,30
000000006,2000522,000500010002,00
000000007,2000613,182236170017,30
  • What is the criterion for the insertion of commas?

  • first comma after 9 characters, second comma after 1 character, third comma after 4 characters

  • Will always follow this padaroo to all the lines

  • which system? Linux or windows?

  • I am using windows

1 answer

2

You can use the php substr function as you read the txt file, like this:

$origem = 'origem.txt';
$destino = 'destino.txt';

$arqOri = fopen($origem, 'r'); // Abre o arquivo de origem para leitura
$arqDes = fopen($destino, 'w'); // Cria o arquivo como destino

while (!feof($arqOri)){
   $str = fread($arqOri);
   $strNovo = substr($str, 0, 9) . ',' .
              substr($str, 9, 7) . ',' .
              substr($str, 15, 12);
   fwrite($arqDes, $strNovo);
}

fclose($arqOri);
fclose($arqDes);

This way you are opening a file, reading line by line and adjusting the information, writing to another file.

In this case, if the destination file exists it will be overwritten with the new content.

  • 1

    It’s a lot of lines, I’d like to pull directly from a.txt file

  • Are you using "fopen" to open the txt file? I will insert in the code an example of how to use it.

  • Yes, I am using

Browser other questions tagged

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