33 Votes

PHP: Read Textarea Line by Line as Array

Question by Guest | Last update on 2022-04-24 | Created on 2018-02-01

I have an HTML form that can be submitted to a PHP script via POST to process the data. Among other things, my form contains a text area in which you can enter several lines of text (with line break).

In my PHP script, I would like to edit each line of the text area individually and not the text as a whole. How can I achieve this and get the content of the textarea line by line into an array?

ReplyPositiveNegativeDateVotes
9Best Answer13 Votes

With the PHP function explode(), you can separate a text at a character or string and get back an array with all parts.

We can pass a line break with \r\n (CR LF / 0D 0A). It is important that we use the double quotes " instead of the simple quotes '. Otherwise PHP will not evaluate \r\n as a line break but as the four characters \, r, \ and n:

$arr = explode("\r\n", trim($_POST['name_of_textarea']));

for ($i = 0; $i < count($arr); $i++) {
   $line = $arr[$i];
   ...
}

The trim() function removes the whitespace from the front and the back of the text from the textarea before passing it to explode(). This will ensure that spaces and empty lines are removed in front and behind, and that our array does not contain additional empty lines later.

Then we can continue to process our array, for example with iterating over all elements of the array with a for-loop and accessing each element individually with $line = $arr[$i] for example.
Last update on 2022-04-24 | Created on 2018-02-01

ReplyPositive Negative
22 Votes

The previous answer is incorrect. [The W3C spec](https://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.1) states that:

> Line breaks, as in multi-line text field values, are represented as CR LF pairs

The modified answer is as follows:

...

$arr = explode("\r\n", trim($_POST['name_of_textarea']));

...
2019-03-05 at 05:22

ReplyPositive Negative
00 Votes

Thank you very much for that correction.

I have corrected the previous answer.
2019-03-05 at 14:38

Positive Negative
Reply
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.