6

I think this code puts a blank line at the end. If that is true, how to avoid this?

$text = explode( "\n", $text );
foreach( $text as $str ) { echo $str; }
Yurié
  • 2,148
  • 3
  • 23
  • 40

3 Answers3

4

Trim the text before you explode it.

$text = trim($text, "\n");
$text = explode( "\n", $text );
foreach($text as $str) {
    echo $str;
}
naththedeveloper
  • 4,503
  • 6
  • 36
  • 44
3

First way is to you trim() function before exploding the string.

$text = trim($text, "\n");
$text = explode( "\n", $text );
foreach( $text as $str ) { echo $str; }

Another way could be using array_filter() after exploding.

$text = explode( "\n", $text );
$text = array_filter($text);
foreach( $text as $str ) { echo $str; }

By default array_filter() removes elements that are equal to false, so there is no need to define a callback as second parameter.

Anyway I think that first way is the best here.

Jakub Matczak
  • 15,341
  • 5
  • 46
  • 64
3

You could, instead of explode, use preg_split with the flag PREG_SPLIT_NO_EMPTY

Example:

$aLines = preg_split('/\n/', $sText, -1, PREG_SPLIT_NO_EMPTY);

But notice that preg_split is slower than explode.

Community
  • 1
  • 1
eXe
  • 662
  • 11
  • 26