Jump to content

Open txt file - Remove all blank lines and save txt file.


Recommended Posts

:confused: Hi Im very new to php. I want to open a file (*.txt) and check for all the blank lines and remove them. and save it as the same file or a new file.

 

I know this can be done using regex. although, I cant seemt to implement regex within a php file.

 

<?php
$file='logz.txt';

$fe = @fopen("$file", "w");
$fe = preg_replace('^\r?\n','',$fe);

fclose($fe);
?>

 

this is what I have, (it might be wrong) but it does not change anything in the logz.txt

I will very greatfull if someone can help me out.

 

 

fopen only returns a handle, it doesn't return the text in the file. To read the text from the file you need to use fread. To write to the file you'll need to use fwrite.

 

Seeing as you're reading and writing to the file you'll need to use w+ as the file mode parameter , rather than using w

A quick (in terms of lines of code at least) would be:

file_put_contents('logs.txt', implode(PHP_EOL, file('logs.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)));

 

If the file is particularly large (i.e. if loading it into memory isn't trivial) then it would be better to go through the file in pieces (like, line-by-line), writing non-empty lines to a temporary file then moving said temporary file to the original location once the process is complete.

Thank you all. teamatomic! your script works fine, I cant believe I couldent figure this out.

salathe, one line ! Wow! thank you. you guys are geniuses. works perfectly. I'm at a very basic level trying to learn PHP.  :D

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.