Changing a certain line of a file with PHP

0

I'm writing an application to change a particular line in an HTML file. I've already been able to find the word I want to replace, but for that, I need the line number to write the new content.

function changeLine(){
    $file = fopen('index.html', 'r+');

     while(!feof($file)) {
         $conteudo = fgets($file);

          if($resultado = preg_match("/<form/", $conteudo)) {
              echo "Achamos!";
          }
     }

    fclose($file);
}

I would like to know if you can capture the line of the HTML file that has the word '.

    
asked by anonymous 20.07.2018 / 23:57

1 answer

0

I was able to change the line this way. In case it was a very specific line.

<?php
         $url = file_get_contents('index.html');
         $var1 = explode("<form", $url);
         $string = array();

         for($i = 0; $i < 81; $i++) {
            $string[0][$i] = $var1[2][$i];
         }

        saveFileOnce();

        foreach($string as $valor => $detalhes) {
            echo $valor;
            foreach($detalhes as $detalhes => $saida) { 
                saveFile($saida);
            }
        }

        $display = changeMethod();
        echo $display;

        // Salva o conteúdo da linha encontrada em um arquivo separado para ser editado.
        function saveFile($texto) {
            $file = fopen('arquivo.txt', 'a');
            fwrite($file, $texto);
            fclose($file);
        }

        function saveFileOnce() {
            $file = fopen('arquivo.txt', 'a');
            fwrite($file, "<");
            fwrite($file, "form");
            fclose($file);
        }

        function changeMethod(){
            $file = file_get_contents('index.html');
            $contents = file_get_contents('arquivo.txt');
            $change = str_replace($contents, "nova linha", $file);
            return $change;
        }

    ?>
    
21.07.2018 / 04:21