Re: Remove blank lines from a file

From: Date: Fri, 21 May 2010 13:25:34 +0000
Subject: Re: Remove blank lines from a file
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-305389@lists.php.net to get a copy of this message
On 5/21/2010 8:03 AM, Anton Heuschen wrote:
Hi Im trying do something like this, have a function which uploads my file and returns file pointer ... but at same time ... I want to remove all Blank lines in a file and update it before it goes to the final location ... What I tried was to do a write of file and use some regexp replace to remove a blank ... either I am not doing the replace correct or my understanding of the file buffer and what I can do with it between the browser and saving is not correct, Anyway my code looks something like this :
  $uploadfile     = $this->uploaddir;
             $mtran          = mt_rand(999,999999);
             $NewName        = date("Ymd_Gis").$mtran.".csv";
             $uploadfile     = $uploadfile.$NewName;
             try{
                 if
(move_uploaded_file($_FILES['attachfile']['tmp_name'], $uploadfile))
                 {
                     $handle = fopen($uploadfile, "r+");
                     $lines  = file($uploadfile,
FILE_SKIP_EMPTY_LINES); //FILE_IGNORE_NEW_LINES |
                     foreach ($lines as $line_num =>  $line) {
                         $line =
preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "", $line);
                         if(strlen($line)>  0)
                             $line=trim($line);
                             $line=$line."\n";
                             fwrite($handle, $line);
                     }
                     fclose($handle);
Suggest using file() which does must of the work for you. Then use foreach() to scan for empty lines. Recreate the array Here is a quickie, not tested. Don't know what is the end of line on empties. So you need to adjust as needed. $orgArray= file(path); foreach($org as $line){
    $tl=trim($line);
    if(empty($tl)) continue;
    $newArray[]=$line;
} file_put_contents($filename, $newArray);

« previous php.general (#305389) next »