You will want to look into the nl2br() function along with the trim(). The nl2br()
will replace the newline character (\n
) with <br />
and the trim()
will remove any ending \n
or whitespace characters.
$text = trim($_POST['textareaname']); // remove the last \n or whitespace character
$text = nl2br($text); // replace \n with <br />
That should do what you want.
UPDATE
The reason the following code will not work is because in order for \n
to be recognized, it needs to be inside double quotes since double quotes parse data inside of them, where as single quotes takes it literally, IE "\n"
$text = str_replace('\n', '<br />', $text);
To fix it, it would be:
$text = str_replace("\n", '<br />', $text);
But it is still better to use the builtin nl2br()
function, PHP provides.
EDIT
Sorry, I figured the first question was so you could add the linebreaks in, indeed this will change the answer quite a bit, as anytype of explode()
will remove the line breaks, but here it is:
$text = trim($_POST['textareaname']);
$textAr = explode("\n", $text);
$textAr = array_filter($text, 'trim'); // remove any extra \r characters left behind
foreach ($textAr as $line) {
// processing here.
}
If you do it this way, you will need to append the <br />
onto the end of the line before the processing is done on your own, as the explode()
function will remove the \n
characters.
Added the array_filter()
to trim()
off any extra \r
characters that may have been lingering.