Thursday, March 09, 2006

Remove blank / empty lines PHP [29]

I found this great implementation to remove blank (empty lines) from a string at PHP web site.


function removeEmptyLines($string)
{
return preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $string);
}

25 comments:

Anonymous said...

Nice. I staved off learning regexes yet another day.

Anonymous said...

You are a wizard indeed! I'm going to try it right now.

Anonymous said...

Awesome. Thanks!

Anonymous said...

Thanks.. this tips is great!

Anonymous said...

Hello, \t ∈ \s — it can be simplified further.

Anonymous said...

Thanks Very Much....
Its Very Userfull...

Thanks


sulistianto.adi@gmail.com
Adi Sulistianto
Indonesia

chavan said...

Thank you very much, i was been trying of hours to get this rid of , your work is really great By chavansoft

Anonymous said...

Yes - this is exactly what I was searcing. Many thanks!!

Br, Kari..

Anonymous said...

This is excellent, it has saved me loads of time, thank you so much!

Bythos said...

This is my solution.
$s = preg_replace('/^\n+|^[\t\s]*\n+/m','',$s);

Anonymous said...

Bythos your code worked. the code from the "topic starter" did not in my case.
Thx. very useful.

BG Hron said...

plug and play perfect, worked like a charm.

Сергей said...

@Bythos thanks! Your solution works for me, topic-starter - not.

Anonymous said...

Very useful

But if you want to remove all duplicated blank lines but want to preserve legibility, just replace, in the RegExp, the first '+' with {2,} and add one more \n in replacement.

Unknown said...

my code is here
it can take care of a folder including sub folders.

http://blog.slesolutions.com/2010/12/blank-line-remover-in-folder-and-subfolders/

Anonymous said...

I like to use an online tool for that: https://www.funender.com/free_online_tools/index.php

Anonymous said...

Oops here is active link: Multiple whitespace remover

Anonymous said...

Amazing ....

Anonymous said...

A thing of beauty that has made me very happy after a frustrating 48 hours coding :) Many thanks.

Anonymous said...

Thanks........

Unknown said...

The purpose of education is to replace an empty mind with an open one. See the link below for more info.

#empty
www.mocsbar.com

oppa said...

Interesting details you have remarked, thank you for putting this article together.

www.triciajoy.com

Unknown said...

I must appreciate your post which is helping us in such a great manner.

Bry
www.gofastek.com

Anonymous said...

If you want each line in an array, with no empty lines, try:

$lines = explode("\n",$multi_line_string);
$lines = array_filter($lines);

Good luck y'all!

Jack said...

good job.
It make me resolve many problems.
So thank you, guys.