从文本区域的输出中删除空行

发布于 2024-10-02 23:55:38 字数 293 浏览 5 评论 0原文

我从文本区域获取数据,用户必须在每一行上输入一个名称。该数据随后在回车符处被分割。有时用户可能会故意添加空行。我怎样才能检测到这些行并删除它们?我正在使用 PHP。我不介意使用正则表达式或其他任何东西。

不正确的数据

Matthew
Mark
Luke

John

James

正确的数据(注意删除空行)

Matthew
Mark
Luke
John
James

I get data from a textarea where a user has to enter a name one on each line. That data later gets split at the carriage return. Sometimes a user may add blank lines intentionally. How can I detect these lines and delete them? I'm using PHP. I dont mind using a regexp or anything else.

Incorrect Data

Matthew
Mark
Luke

John

James

Correct Data (Note blank lines removed)

Matthew
Mark
Luke
John
James

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

作死小能手 2024-10-09 23:55:38

使用正则表达式消除爆炸之前的空行(适用于任意数量的连续空行,另请参阅下一个片段):

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

使用正则表达式进行拆分:

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

不使用正则表达式进行拆分:

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

今天感觉有点创意,选择你的毒药:)

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 :)

铁憨憨 2024-10-09 23:55:38

我相信,简单的字符串替换应该可以解决问题。

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

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

str_replace("\r\n\r\n", "\r\n", $text);
夏至、离别 2024-10-09 23:55:38

分割输入后,循环数组搜索空行:

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

您甚至可以查找只包含空格的行来删除它们:(

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

两个代码片段都未经测试)

注意:按换行符分割时要小心(我用 \n 分割它们) ,但如果客户端浏览器在 Windows 上运行,则可能为 \r\n)。

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文