RE: [PHP] Remove blank lines from a file
| From: | Bob McConnell | Date: | Fri, 21 May 2010 15:08:54 +0000 |
| Subject: | RE: [PHP] Remove blank lines from a file | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-305399@lists.php.net to get a copy of this message | ||
From: Anton Heuschen
> On 21 May 2010 15:16, Ashley Sheridan <ash@ashleysheridan.co.uk>
wrote:
>> On Fri, 2010-05-21 at 14:03 +0200, 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);
>>
>>
>>
>> If the files aren't too large in size, what about using something
like
>> file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
which
>> should pull into an array only those lines with content, and then
just write
>> that back out to the same file line by line?
>
> I actually had that ... removed it in last example as I was trying
other
> stuff and it did not seem to work either ?
>
> $lines = file($uploadfile, FILE_SKIP_EMPTY_LINES);
//FILE_IGNORE_NEW_LINES
> |
>
>
> see I removed the FILE_IGNORE line - it was in earlier and only tried
> FILE_SKIP_EMPTY .... but still the final file had all the spaces again
...
>
> So in the file it would look like (from the original file the user
uploads
> that is)
>
> 1
> 2
>
> 3
> 4
>
>
> 5
>
> 6
>
>
> but when the file is saved to the server it must look like
>
>
> 1
> 2
> 3
> 4
> 5
> 6
>
> but it never does and still looks like the first block.
Are those lines actually empty, or do they have other non-printing
characters in them? Isn't there a generic whitespace value that could be
used in place of '\s\t'?
Can you look at the output file with a binary or hex editor to see what
is actually in those 'empty' lines?
Does that regular expression work correctly on UTF-8 input?
Bob McConnell