Jump to content

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


new2code

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.

 

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.