To perform the substitution you can use the str_replace
or preg_replace
.
In this case just change to:
<?php
//...
if(preg_match("/arquivo.txt/",$le)){
$conteudo = str_replace("arquivo.txt", "novo_arquivo.txt", $le);
// Alternativa: preg_replace("/\barquivo.txt\b/", "novo_arquivo.txt", $le);
// Substitui o arquivo.txt por novo_arquivo.txt
fwrite($aq, $conteudo);
// Escreve o conteúdo editado.
}
//..
?>
Optimal solution:
Abandon the fopen
, will be easier and will not have so much loss of performance.
<?php
//...
foreach ($arquivos as $caminho){
$conteudoArquivo = file_get_contents($caminho);
// Isso irá pegar todo o conteudo do arquivo
if(preg_match("/arquivo.txt/", $conteudoArquivo)){
// Se existir arquivo.txt
$conteudoEditado = str_replace("arquivo.txt", "novo_arquivo.txt", $conteudoArquivo);
// Novo $conteudoEditado terá a alteração
file_put_contents($caminho, $conteudoEditado);
// Salva as alterações
}
}
//..
?>
Important (function feof()
):
There are some cases where the feof()
can create an infinite loop, even there are examples in the PHP documentation, which can be accessed clicking here.
Could you be more clear in your doubt? I don’t understand
– Victor Eyer
I saw that you are a new user, so don’t take this personally, but consider changing or detailing the functions/variables. It’s extremely exhausting to be looking for what would be
$le
,$a
,$aq
and things that are never used, for example$nomeArquivo
, which confuses me even more. In a next post consider giving more details, essentially within the code itself, with small changes, so you can get even better and faster answers. :)– Inkeliz
Thanks for the tips, I’ll do it next time . thank you very much for the willingness to help me.
– Lenilson Teixeira