PHP explode() - how to avoid blank lines? [duplicate]
Asked Answered
H

3

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; }
Horrify answered 1/2, 2014 at 21:15 Comment(1)
Trim the text before you explode it? $text = trim($text, "\n");Pharynx
B
4

Trim the text before you explode it.

$text = trim($text, "\n");
$text = explode( "\n", $text );
foreach($text as $str) {
    echo $str;
}
Bernardinebernardo answered 1/2, 2014 at 21:17 Comment(0)
R
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.

Restitution answered 1/2, 2014 at 21:18 Comment(0)
P
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.

Pycnometer answered 26/11, 2015 at 10:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.