How to Remove the First Blank Line in PHP

In a large, multi-file PHP application, blank lines can trigger PHP warning and error messages. Some PHP functions require that they be executed prior to any output being sent by the program. If you hit the "Enter" key after the PHP closing tag at the end of a PHP file, the Web server will interpret that as outputting a blank line to the screen. This will generate warnings or errors if you then execute a function that must be run before any output is generated. You can use PHP to open PHP files and remove the first blank line after a PHP closing tag.

Instructions

    • 1

      Store the name of the file from which you want to remove the first blank line in a variable. Check to make sure the file exists before you attempt to read it. For example, type:

      <?php

      $program_file = "program.php";

      if (!file_exists($program_file)) die($program_file. " does not exist!");

    • 2

      Read the entire contents of the file into a string variable. Close the file after you've read the contents. For example, type:

      $contents = file_get_contents($program_file);

      fclose($program_file);

    • 3

      Call the preg_replace function with a regular expression that matches a blank line after a closing PHP tag and replace the first instance of a blank line with null in the variable that holds the file contents. For example, type:

      $new_contents = preg_replace("/^>\?\r\n", "", $contents, 1);

    • 4

      Compare the original contents of the file with the contents after replacing the first blank line. Advise the user that no blank line existed if they are the same. For example, type:

      if ($contents == $new_contents) {

      echo "No blank line existed in ". $program_file;

      }

    • 5

      Open the program file in write mode. Write the contents of the variable with the blank line removed to the file. Close the file and advise the user of the program's result. For example, type:

      else {

      $fh = fopen($program_file, "w");

      fputs($fh, $new_contents);

      fclose($fh);

      echo "Removed first blank line in " . $program_file;

      }

      ?>

Related Searches:

References

Resources

Comments

You May Also Like

Related Ads

Featured