Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove blank lines from text in PHP?

Tags:

regex

php

I need to remove blank lines (with whitespace or absolutely blank) in PHP. I use this regular expression, but it does not work:

$str = ereg_replace('^[ \t]*$\r?\n', '', $str); $str = preg_replace('^[ \t]*$\r?\n', '', $str); 

I want a result of:

blahblah  blahblah     adsa    sad asdasd 

will:

blahblah blahblah    adsa  sad asdasd 
like image 277
StoneHeart Avatar asked Apr 02 '09 13:04

StoneHeart


People also ask

How do you remove blank lines in a text?

Open TextPad and the file you want to edit. Click Search and then Replace. In the Replace window, in the Find what section, type ^\n (caret, backslash 'n') and leave the Replace with section blank, unless you want to replace a blank line with other text. Check the Regular Expression box.

How do I permanently delete blank lines?

The d command in sed can be used to delete the empty lines in a file.

How do I get rid of extra lines in HTML?

Accepted Answerhtml = Regex. Replace(html, @"( |\t|\r?\ n)\1+", "$1");


1 Answers

// New line is required to split non-blank lines preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $string); 

The above regular expression says:

/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/     1st Capturing group (^[\r\n]*|[\r\n]+)         1st Alternative: ^[\r\n]*         ^ assert position at start of the string             [\r\n]* match a single character present in the list below                 Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]                 \r matches a carriage return (ASCII 13)                 \n matches a fine-feed (newline) character (ASCII 10)         2nd Alternative: [\r\n]+             [\r\n]+ match a single character present in the list below             Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]             \r matches a carriage return (ASCII 13)             \n matches a fine-feed (newline) character (ASCII 10)     [\s\t]* match a single character present in the list below         Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]         \s match any white space character [\r\n\t\f ]         \tTab (ASCII 9)     [\r\n]+ match a single character present in the list below         Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]         \r matches a carriage return (ASCII 13)         \n matches a fine-feed (newline) character (ASCII 10) 
like image 100
Michael Wales Avatar answered Oct 04 '22 05:10

Michael Wales