Overwrite file snippet with php?

Asked

Viewed 1,672 times

2

I don’t know how to explain my problem, so I’ll illustrate:

I’m using PHP and would like to manipulate a file . txt of n lines. Each line has a standard size of 20 characters.

For example... the first 8 characters refer to a shipping date (ddmmaaa), the 2 next to the state of origin (SP, RJ, ...), the other 2 to the destination state and the last 8 to the product code.

Linha 1: 01012014RJPA00001472
Linha 2: 03121997MGRS00192010
...
Linha n: 28092012AMAC00000071

What I’d like to know is how to overwrite one of these terms (not the entire line, not the entire file) and save the file.

Type: On line 2 of the file I want to change the source state from MG to MT without changing the other file data. As if I took the pointer to a position before the 'MG' press the keyboard insert and type 'MT'.

  • if you want to work with data in this way I advise you to see about xml http://www.w3schools.com/xml/

3 answers

1

It would be interesting if you used regular expressions for this.

You said your text file is composed of lines in the following format:

  • 20 characters each
  • the first 10 characters are dates, irrelevant to our purposes
  • the following 2 characters are the UF, since we want to work
  • the following 8 characters are also irrelevant

Therefore, the basic regular expression for each line would be:

/^(?P<data>.*){10}(?P<uf>.*){2}(?P<etc>.*){8}$/

To replace this data, just use the function preg_replace:

$siglaABuscar = 'MT';
$novaSigla    = 'MG';
$arquivo      = file_get_contents('arquivo.txt');
$arquivo      = preg_replace("/^(?P<data>.*){10}(?P<uf>$siglaABuscar){2}(?P<etc>.*){8}$/g", "$1$novaSigla$3", $arquivo);
file_put_contents('arquivo.txt', $arquivo);

PS: I wrote the code from the head, there may be some adjustments to be made.

  • I have not tested the code, nor have I ever used regular expressions with PHP. I may be mistaken, but I think in this code I would change all the 'MT' of the file to 'MG'. I wanted to change just that specific second line. Type I would use a fgets() to carry the pointer to that position and use a fputs(), or some way of overwriting, to write the 2 new characters 'above' of the old ones.

  • @Hiranfilho I think what you can do is use the function file, which loads the file into an array in which each key contains a file row. Then, you would change only the key 1 (which would correspond to the second line) using the input parameters MT (which corresponds to the acronym to be sought) and MG (which corresponds to the new acronym).

1


There are several ways... What you asked for, I believe is basically this:

<?php

// Tamanho padrão da sua linha
$linha_tamanho_default = 20;

// Array que define o inicio do valor na linha de acordo com o tipo de dado
$inicio = array(
    "DATA" => 0,
    "UF" => 8,
    "DESTINO" => 10,
    "CODIGO" => 12,
);

// Define o tamanho de cada item de acordo com o tipo de dado
$tamanho = array(
    "DATA" => 8,
    "UF" => 2,
    "DESTINO" => 2,
    "CODIGO" => 8,
);

// simulando o arquivo em uma string
// equivale a um arquivo txt com o conteudo do comentário abaixo:
/* 
01012014RJPA00001472
03121997MGRS00192010
28092012AMAC00000071
*/
$arquivo = "01012014RJPA00001472\n03121997MGRS00192010\n28092012AMAC00000071";


/***** Abaixo os parâmetros definem que a UF da 3ª linha será substituida por RJ */

// Define que TIPO de valor será substituido
$tipo = "UF";
// Define a linha que será alterada
$linha = 3;
// Define o NOVO valor
$valor = "RJ";

// Calcula a posição para a substituição
// usa $linha-1 (pois a contagem inicia em 0)
// usa $linha_tamanho_default+1 (pois inclui o \n)
// soma com o inicio do item que deseja substituir de acordo com a linha
$posicao = ($linha-1)*($linha_tamanho_default+1) + $inicio[$tipo];

// Retorna o arquivo   
$arquivo = substr_replace($arquivo, $valor, $posicao, $tamanho[$tipo] );

// Printa os resultados
echo $arquivo;

?>

0

Here are some tips that might help

fopen(), fread(), fgets(), fwrite(), fclose() methods are used to access and change files in your php script. http://br.php.net/manual/en/function.fopen.php

Another option is to "pull everything to an array", make the changes, and then re-write the file. (If there are too many checks and changes, it may be a good option)

$arrayDeLinhas = file($filename, FILE_IGNORE_NEW_LINES);

This will give you an array of the file lines, then you can handle the information as you wish.

Here you can find a method to help you handle the string. http://php.net/manual/en/book.strings.php

I believe wordwrap and substr_replace should help you. But from now on it’s your algorithm organization, so it’s up to you!

Browser other questions tagged

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