51
<textarea> put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
quote by placing > at start of line
</textarea>

$text = value from this textarea;

How to:

1) Get each line from this textarea ($text) and work with them using foreach()?

2) Add <br /> to the end of each line, except the last one?

3) Throw each line to an array.

Important - text inside textarea can be multilanguage.


Have tried to use:

$text = str_replace('\n', '<br />', $text);

But it doesn't work.


Thanks.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
James
  • 42,081
  • 53
  • 136
  • 161

8 Answers8

110

Warning: this answer is focused on the particular part of OP, which is not related to the question title. For the answer to the question "how to get each line", consider the posts below.

You will want to look into the nl2br() function along with the trim().

The nl2br() will insert <br /> before the newline character (\n) 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); // insert <br /> before \n 

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($textAr, '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.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Jim
  • 18,673
  • 5
  • 49
  • 65
  • what about the first question? – James Sep 13 '10 at 16:36
  • The above code is assuming that you are grabbing the data from the textarea using a form you setup. If you have the HTML data and you would like to parse that, see shamittomar's answer. – Jim Sep 13 '10 at 16:41
  • @premiso I want to parse my own textarea, from $_POST – James Sep 13 '10 at 16:43
  • The reason for the double quotes is that they parse data inside the string, where as single quotes takes data literally. – Jim Sep 13 '10 at 16:44
  • 3
    No, `explode` doesn't use regular expressions. If you want to split strings based on RE, use `preg_split` instead. – poke Sep 13 '10 at 16:49
  • 2
    Happy, I did an edit, you can do an `array_filter` with `trim` which will trim off any extra `\r` characters that were left behind. Or as poke said, use the `preg_split`. – Jim Sep 13 '10 at 16:50
  • In your example I think array_filter($text, 'trim') should be changed to array_filter($textAr, 'trim'). – Chris Mar 18 '13 at 00:12
  • $textAr = explode("\n", $text); worked for me when i try to foreach the textarea. should be double quotes ("") instead of quotes (''). – fudu Jun 29 '21 at 08:24
45

You could use PHP constant:

$array = explode(PHP_EOL, $text);

additional notes:
1. For me this is the easiest and the safest way because it is cross platform compatible (Windows/Linux etc.)
2. It is better to use PHP CONSTANT whenever you can for faster execution

Shah Erhan
  • 573
  • 5
  • 7
10

Old tread...? Well, someone may bump into this...

Please check out http://telamenta.com/techarticle/php-explode-newlines-and-you

Rather than using:

$values = explode("\n", $value_string);

Use a safer method like:

$values = preg_split('/[\n\r]+/', $value_string);
Temitope
  • 101
  • 1
  • 2
  • 1
    Good point. [Shah Erhan](http://stackoverflow.com/a/7870846/4012426) suggested using `PHP_EOL`, but I don't know if the end-of-line characters sent by browsers always equate to the end-of-line characters on the server. Your link is horribly broken, by the way. – Hutch Moore Jun 09 '16 at 15:31
  • 1
    This was the best solution, the other solutions did not remove the `\r` from the end of the line. – tinyCoder Jun 16 '20 at 00:00
5

Use PHP DOM to parse and add <br/> in it. Like this:

$html = '<textarea> put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
quote by placing > at start of line
</textarea>';

//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('textarea');

//get text and add <br/> then remove last <br/>
$lines = $nodes->item(0)->nodeValue;

//split it by newlines
$lines = explode("\n", $lines);

//add <br/> at end of each line
foreach($lines as $line)
    $output .= $line . "<br/>";

//remove last <br/>
$output = rtrim($output, "<br/>");

//display it
var_dump($output);

This outputs:

string ' put returns between paragraphs
<br/>for linebreak add 2 spaces at end
<br/>indent code by 4 spaces
<br/>quote by placing > at start of line
' (length=141)
shamittomar
  • 46,210
  • 12
  • 74
  • 78
  • +1 as he may be wanting to parse HTML, and if so this is a better way of doing it. But not sure if that is his intentions. – Jim Sep 13 '10 at 16:43
  • I'm parsing my own textarea from $_POST – James Sep 13 '10 at 16:46
  • @shamittomar Probably because your answer doesn't answer the question. James is getting the value from `$_POST`, not parsing a string with HTML tags. The way the question is written, your confusion is understandable, though. (I wasn't the down-voter.) – Hutch Moore Jun 08 '16 at 20:29
  • Slick solution for not having a trailing break tag. For "all except the last" loops I normally check `$i` against the total length, inside the loop. – Hutch Moore Jun 08 '16 at 20:30
5

It works for me:

if (isset($_POST['MyTextAreaName'])){
    $array=explode( "\r\n", $_POST['MyTextAreaName'] );

now, my $array will have all the lines I need

    for ($i = 0; $i <= count($array); $i++) 
    {
        echo (trim($array[$i]) . "<br/>");
    }

(make sure to close the if block with another curly brace)

}
Hutch Moore
  • 124
  • 1
  • 12
profimedica
  • 2,716
  • 31
  • 41
4

For a <br> on each line, use

<textarea wrap="physical"></textarea>

You will get \ns in the value of the textarea. Then, use the nl2br() function to create <br>s, or you can explode() it for <br> or \n.

Hope this helps

Hutch Moore
  • 124
  • 1
  • 12
Alexander_F
  • 2,831
  • 3
  • 28
  • 61
4
$array = explode("\n", $text);
for($i=0; $i < count($array); $i++)
{
    echo $line;
    if($i < count($array)-1)
    {
         echo '<br />';
    }
}
cichy
  • 10,464
  • 4
  • 26
  • 36
4
$content = $_POST['content_name'];
$lines = explode("\n", $content);

foreach( $lines as $index => $line )
{
    $lines[$index] = $line . '<br/>';
}

// $lines contains your lines
Vincent Robert
  • 35,564
  • 14
  • 82
  • 119
  • thanks Robert, can you explain this part of code "$index => $line"? – James Sep 13 '10 at 16:49
  • 1
    foreach( $lines as $index => $line ) == "for each element of $lines, iterate with $index containing the key/index and $line containing the value" http://fr.php.net/manual/en/control-structures.foreach.php ... (Actually, my first name is Vincent ^^) – Vincent Robert Sep 13 '10 at 16:56