Re: Remove blank lines from a file

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 





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);

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux