38

can I do:

explode("\n", $_POST['thetextarea']);

and have it work on all platforms? (The question I am asking is will it ever be \r\n and not just \n")

EDIT:

I forgot to mention that I am saving $_POST['thetextarea'] to a mysql database VARCHAR 255. It seems \r\n is converted to \n.

Chris Muench
  • 17,444
  • 70
  • 209
  • 362
  • 1
    possible duplicate of http://stackoverflow.com/questions/760282/do-line-endings-distinctions-apply-for-html-forms – Arnaud Le Blanc Aug 14 '11 at 16:44
  • If the text field contains `\r\n` then spliting on newlines would still work, and just keep extraneous carriage returns in the lines. – mario Aug 14 '11 at 16:45

4 Answers4

101

This will do the trick given \r\n, \r or \n:

preg_split('/\r\n|[\r\n]/', $_POST['thetextarea'])
Long Ears
  • 4,886
  • 1
  • 21
  • 16
24

You should use:

explode("\r\n", $_POST['thetextarea']);

It will always be the same.

Browsers and other user-agents will make sure they are :-)

See http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.1 for more info.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
  • 1
    Not all user agents are browsers however. – mario Aug 14 '11 at 16:54
  • @mario: also according to the HTML5 spec (draft I know) lines are terminated by `CRLF`. http://dev.w3.org/html5/spec/Overview.html#the-textarea-element if I'm correct – PeeHaa Aug 14 '11 at 17:09
  • new link is http://w3c.github.io/html/sec-forms.html#the-textarea-element – piotr_cz Sep 30 '18 at 17:51
12

You could also use the PHP_EOL constant:

explode(PHP_EOL, $_POST['thetextarea']);
Sascha Galley
  • 15,711
  • 5
  • 37
  • 51
  • 12
    wouldn't PHP_EOL just use the linebreak of the current platform? If so, you don't want it here :) – PeeHaa Aug 14 '11 at 16:53
2

You can do something like this:

$text = trim($_POST['textareaname']);
$text = nl2br($text);
Rich Benner
  • 7,873
  • 9
  • 33
  • 39
  • 1
    "It's important to remember that this function does NOT replace newlines with
    tags. Rather, it inserts a
    tag before each newline, but it still preserves the newlines themselves!" - guy at php.net manual
    – Robbe May 06 '17 at 20:55