Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

php - Get each line from textarea

<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('
', '<br />', $text);

But it doesn't work.


Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

The nl2br() will insert <br /> before the newline character ( ) and the trim() will remove any ending or whitespace characters.

$text = trim($_POST['textareaname']); // remove the last 
 or whitespace character
$text = nl2br($text); // insert <br /> before 
 

That should do what you want.

UPDATE

The reason the following code will not work is because in order for 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 " "

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

To fix it, it would be:

$text = str_replace("
", '<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("
", $text);
$textAr = array_filter($textAr, 'trim'); // remove any extra 
 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 characters.

Added the array_filter() to trim() off any extra characters that may have been lingering.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...