Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP explode() - how to avoid blank lines?

Tags:

php

explode

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; }
like image 799
Iurie Avatar asked Feb 01 '14 21:02

Iurie


Video Answer


3 Answers

Trim the text before you explode it.

$text = trim($text, "\n");
$text = explode( "\n", $text );
foreach($text as $str) {
    echo $str;
}
like image 101
naththedeveloper Avatar answered Sep 19 '22 00:09

naththedeveloper


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.

like image 44
Jakub Matczak Avatar answered Sep 21 '22 00:09

Jakub Matczak


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.

like image 27
eXe Avatar answered Sep 18 '22 00:09

eXe