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; }
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; }
Trim the text before you explode it.
$text = trim($text, "\n");
$text = explode( "\n", $text );
foreach($text as $str) {
echo $str;
}
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.
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
.
© 2022 - 2024 — McMap. All rights reserved.
$text = trim($text, "\n");
– Pharynx