explode textarea php (at new lines)
Asked Answered
F

4

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.

Fa answered 14/8, 2011 at 16:42 Comment(2)
possible duplicate of #760782Lawton
If the text field contains \r\n then spliting on newlines would still work, and just keep extraneous carriage returns in the lines.Efthim
T
101

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

preg_split('/\r\n|[\r\n]/', $_POST['thetextarea'])
Tradition answered 14/8, 2011 at 16:56 Comment(2)
Yup. Worked for me too, not the \r\n one.Begat
with a bit difference worked for me, double quote instead of single "/\r\n|[\r\n]/" and I don't know whyConcession
O
25

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.

Olenta answered 14/8, 2011 at 16:47 Comment(3)
Not all user agents are browsers however.Efthim
@mario: also according to the HTML5 spec (draft I know) lines are terminated by CRLF. dev.w3.org/html5/spec/Overview.html#the-textarea-element if I'm correctOlenta
new link is w3c.github.io/html/sec-forms.html#the-textarea-elementLongdrawn
B
12

You could also use the PHP_EOL constant:

explode(PHP_EOL, $_POST['thetextarea']);
Butchery answered 14/8, 2011 at 16:47 Comment(1)
wouldn't PHP_EOL just use the linebreak of the current platform? If so, you don't want it here :)Olenta
S
2

You can do something like this:

$text = trim($_POST['textareaname']);
$text = nl2br($text);
Spine answered 23/6, 2016 at 7:10 Comment(1)
"It's important to remember that this function does NOT replace newlines with <br> tags. Rather, it inserts a <br> tag before each newline, but it still preserves the newlines themselves!" - guy at php.net manualLaodicea

© 2022 - 2024 — McMap. All rights reserved.