从textarea获取每一行 [英] Get each line from textarea

查看:195
本文介绍了从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;

方法:

1)从此文本区域($text)中获取每一行,并使用foreach()进行处理?

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

2)在每行的末尾添加<br />,最后一行除外?

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

3)将每一行扔到一个数组中.

重要-文本区域内的文本可以是多语言.

Important - text inside textarea can be multilanguage.

尝试使用:

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

但这是行不通的.

谢谢.

推荐答案

您将需要研究 nl2br() 函数以及 trim().

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

nl2br()将在换行符(\n)之前插入<br />,并且trim()将删除任何结尾的\n或空格字符.

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 

那应该做你想要的.

更新

以下代码不起作用的原因是,为了识别\n,它必须在双引号内,因为双引号会解析其中的数据,其中单引号实际上就是IE

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);

但是最好使用PHP提供的内置nl2br()函数.

But it is still better to use the builtin nl2br() function, PHP provides.

编辑

对不起,我发现第一个问题是,您可以添加换行符,实际上这会改变答案,因为任何类型的 explode() 将删除换行符,但这是:

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. 
} 

如果以这种方式进行操作,则需要单独将<br />附加到行的末尾,因为explode()函数将删除\n字符.

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.

trim()中添加了 array_filter() trim()中,这些字符可能已经被删除了.挥之不去.

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

这篇关于从textarea获取每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆