问题
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
回答1:
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 :)
回答2:
A simple string replace should do the trick, I believe.
str_replace("\r\n\r\n", "\r\n", $text);
回答3:
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).
来源:https://stackoverflow.com/questions/4214685/removing-blank-lines-from-a-textareas-output