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

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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...


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux