Removing blank lines from a textarea's output

♀尐吖头ヾ 提交于 2019-11-28 11:49:53

Using regex to eliminate blank lines before exploding (works well for any number of consecutive blank lines, also see next snippet):

$text = preg_replace('/\n+/', "\n", trim($_POST['textarea']));

Splitting with a regex:

$lines = preg_split('/\n+/', trim($_POST['textarea']));
$text = implode("\n", $lines);

Splitting without a regex:

$lines = array_filter(explode("\n", trim($_POST['textarea'])));
$text = implode("\n", $lines);

Just feeling a tad creative today, pick your poison :)

A simple string replace should do the trick, I believe.

str_replace("\r\n\r\n", "\r\n", $text);

After splitting your input, loop the array searching for empty lines:

$lines = explode("\n", $_POST['your_textarea']);
foreach ($lines as $k=>$v) if(empty($v)) unset($lines[$k]);

You could even look for lines containing just spaces to also delete them:

$lines = explode("\n", $_POST['your_textarea']);
foreach ($lines as $k=>$v) if(empty(trim($v))) unset($lines[$k]);

(Both code snippets are untested)

NOTE: Be careful when splitting by line breaks (I splitted them by \n, but could be \r\n if the client browser runs on Windows).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!