1

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
ajreal
  • 46,720
  • 11
  • 89
  • 119
Norman
  • 6,159
  • 23
  • 88
  • 141

3 Answers3

12

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

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • Great answer. And since Norman needs the data as an array, `preg_split('/\n+/', trim($_POST['textarea']))` is all he needs. – Joost Nov 18 '10 at 12:43
  • @JoostK: Well, you're right. My code now separates `$lines` from `$text` appropriately so it's easier to follow. – BoltClock Nov 18 '10 at 12:47
  • Sorry, but the last code block wont work. We will be getting a `1 byte` space for empty lines, and hence `array_filter` wont cut it. Please correct it :) – Kishor May 26 '15 at 03:24
  • `$lines = array_filter(array_map('trim',explode("\n",($_POST['textarea'])))); `that will do it. – Kishor May 26 '15 at 03:30
0

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

str_replace("\r\n\r\n", "\r\n", $text);
BeemerGuy
  • 8,139
  • 2
  • 35
  • 46
  • 1
    Doing this in a single pass will convert 3 newlines to 2, and so on. You could use `while (strpos($text, "\r\n\r\n") !== false)` to check. – BoltClock Nov 18 '10 at 12:35
0

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

pau.moreno
  • 4,407
  • 3
  • 35
  • 37