Re: how to strip empty lines out of a txt using preg_replace()

From: Date: Fri, 04 Sep 2009 22:02:18 +0000
Subject: Re: how to strip empty lines out of a txt using preg_replace()
References: 1 2 3 4 5 6  Groups: php.general 
Request: Send a blank email to php-general+get-297704@lists.php.net to get a copy of this message
Sam Stelfox wrote: > The following snippet is untested and using Ash's regex (it is accurate > \s matches any white space). $content is what is getting stripped of the > new lines and $filtered is the cleansed output. See if that does the > trick for you. > > $lines = str_split(PHP_EOL, $content); > $filtered = ''; > foreach ($lines as $line) { > if (!preg_match('^\s*$', $line)) { > // Splitting on the PHP_EOL characters cause it to be removed be > sure to put it back > $filtered .= $line . PHP_EOL; > } > } > That isn't going to work. You missed your delimiters in the first arg for preg_match(). It requires beginning and ending delimiters around the regex. I would try this $lines = preg_split('|[\n\r]|', $content); $filtered = ''; foreach ( $lines as $line ) { $txt = trim( $line ); if ( ! empty( $txt ) ) { $filtered .= $line; } } It is much more intense to do the preg_match inside a loop. You should only do it once, then use less intense function calls inside the loop. warning: completely untested... have no example input you are using...

« previous php.general (#297704) next »