How to find a link inside an html file and switch to another link?

6

So far I've only been able to find out if a link exists in the file, but I do not know how to do the exchange. My code is this:

$nomeArquivo = $_POST['nomeArquivo'];


foreach ($arquivos as $a){
$aq = fopen($a,"r+");
while (!feof($aq)){
    $le = fgets($aq);

    if(preg_match("/arquivo.txt/",$le)){

        //realizar troca
       //salvar arquivo
    }

}
fclose($aq);
}
    
asked by anonymous 08.02.2016 / 02:52

2 answers

2

To perform the substitution you can use 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.

    }
//..
?>

Ideal solution:

Quit fopen , it will be easier and you will not have as much performance loss.

<?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 feof() can create an infinite loop, there are even examples in the PHP documentation, which can be accessed by clicking here .

    
08.02.2016 / 03:46
0

It is not clear because depending on what needs to be done there are several ways to solve.

For example, if you just want to change a specific string on all links, you can use str_replace() and save with file_put_contents() . Nor would it have to open with fopen() and search with regex . But as I said, it depends on what really needs to be done.

Example, if you just want to replace one string with another within the contents of a file:

file_put_contents(str_replace('nome-antigo.txt', 'nome-novo.txt', file_get_contents($caminho_do_arquivo)));
    
08.02.2016 / 17:17