本文介绍了从文本区域的输出中删除空白行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从文本区域获取数据,用户必须在每一行中输入一个名字.稍后,该数据在回车时被拆分.有时用户可能会故意添加空白行.如何检测并删除这些行?我正在使用PHP.我不介意使用正则表达式或其他任何东西.
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.
数据不正确
Matthew
Mark
Luke
John
James
更正数据(注意删除了空白行)
Matthew
Mark
Luke
John
James
推荐答案
使用正则表达式消除 爆炸前的空行(对于任意数量的连续空行都有效,另请参见下一个片段):
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']));
使用正则表达式分割
$lines = preg_split('/\n+/', trim($_POST['textarea']));
$text = implode("\n", $lines);
不使用正则表达式分割
$lines = array_filter(explode("\n", trim($_POST['textarea'])));
$text = implode("\n", $lines);
今天刚感觉有点创意,请选择毒药:)
Just feeling a tad creative today, pick your poison :)
这篇关于从文本区域的输出中删除空白行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!