简体   繁体   English

使用PHP检测文本区域中的回车符/换行符

[英]Detect a carriage return/new line in a text area with PHP

How do I detect a carriage return/new line character in a text area in PHP? 如何在PHP中检测文本区域中的回车符/换行符?

I want to replace them with <br /> tags before storing it in the database. 我想在将它们存储到数据库之前用<br />标签替换它们。

There's a php constant for this: 有一个PHP常量:

When do I use the PHP constant "PHP_EOL"? 我什么时候使用PHP常量“PHP_EOL”?

Also look into nl2br() . 另请查看nl2br()

My advice: "don't do it". 我的建议是:“不要这样做”。 Just store the line breaks in the db, but render it to <br /> only when producing the output. 只需在数据库中存储换行符,但仅在生成输出时将其呈现为<br /> Otherwise you'll have the problem of replacing the <br /> when you want to use that data in a different context. 否则,当您想在不同的上下文中使用该数据时,您将遇到替换<br />的问题。

For that, you can use nl2br See: http://php.net/manual/en/function.nl2br.php 为此,你可以使用nl2br参见: httpnl2br

Just nl2br it ;) 只是nl2br它;)

PS: Don't apply the function when inserting to the database (use only SQL escaping here). PS:插入数据库时​​不要应用该函数(此处仅使用SQL转义)。 Apply the function as soon as you want to output the text to HTML. 只要您想要将文本输出到HTML,请立即应用该功能。

I know this is v-old but just wanted to make a note here, perhaps even for myself! 我知道这是v-old,但只是想在这里做一个笔记,甚至可能是为了我自己! The eols here need to be in double quotes, otherwise It just won't work. 这里的eols需要用双引号,否则它就行不通。 See below... 见下文...

$eols = array(",","\n","\r","\r\n");
$text_area = str_replace($eols,'<br />',$_POST['text_area']);

Hope this helps someone not waste time like I just did for 30mins! 希望这可以帮助别人不要像我刚做的那样浪费时间30分钟!

You may use nl2br() . 你可以使用nl2br() Please note that it will convert \\n and \\r\\n to <br />\\n . 请注意,它会将\\n\\r\\n转换为<br />\\n

You can use the nl2br() function. 您可以使用nl2br()函数。 This will insert <br/> as necessary. 这将插入<br/>是必要的。

It is generally my preference to leave the HTML formatting out of the DB (unless it was in the source material). 通常我倾向于将HTML格式保留在DB之外(除非它在源材料中)。 You never know when you may want to use the clean version for other purposes. 您永远不知道何时可能希望将干净版本用于其他目的。

Try this: 尝试这个:

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

Using str_replace 使用str_replace

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM