PHP explode () - how to avoid empty lines?

I think this code puts an empty string at the end. If so, how to avoid this?

$text = explode( "\n", $text );
foreach( $text as $str ) { echo $str; }
+4
source share
3 answers

Trim the text before blowing it up.

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

The first way is a function trim()before blowing up a string.

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

Another way could be use array_filter()after an explosion.

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

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

Anyway, I think the best way is best here.

+2
source

explode preg_split PREG_SPLIT_NO_EMPTY

:

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

, preg_split , explode.

+2

Source: https://habr.com/ru/post/1524881/


All Articles