Change a certain line in a PHP file

Asked

Viewed 410 times

0

I’m writing an application to change a particular line in an HTML file. I’ve been able to locate 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 wonder if it is possible to capture the line of the HTML file that has the word '<'form.

  • Instead of finding the line, wouldn’t it be better to replace what you want to change? You read the file and save it to a variable, replace and write the file again.

  • It could be too! I was trying to find a way to do this, I would have to make the change using the right fwrite?

  • I believe so...

  • Already asked here: How to change a specific line of a php file - In the comments you almost have the solution (just replace).

  • Brawl! I’ll take a look :)

1 answer

0

I managed to change the line this way. In the 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;
        }

    ?>

Browser other questions tagged

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