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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top