繁体   English   中英

如何更换新线

[英]How to replace new line

$t = '"Confidence isn\'t gained over time and practice. Confidence is gained when you realize you choose your own path, you choose to fall, you choose not to fall.

If you are afraid to fall you fall because you are afraid. Everything is choice." - Daniel ILabaca';
$order   = array("\r\n", "\n", "\r");
$text = str_replace($order, '<br/>', $t);

但是在数据库中仍然是新行。

在插入之前,我先做htmlspecialchars(addslashes(trim($text)))

为什么不使用nl2br()函数呢? 尝试这个:

$text = nl2br($t);

而不是以下两行:

$order   = array("\r\n", "\n", "\r");
$text = str_replace($order, '<br/>', $t);

在将数据保存到DB中时, 仅需对其进行转义以防止SQL注入 无需执行htmlspecialchars,nl2br,addslashes等。您可以按原样保存用户数据。 但是请确保其安全。 在展示层显示此数据时,应使用htmlentities,nl2br,addslashes等函数

如果你不希望在所有任何换行符,不想把他们转换为HTML <br >看看这个位置: 从HTML源代码中删除所有的换行符

您应该使用PHP内置方法nl2br()

nl2br — Inserts HTML line breaks before all newlines in a string 

<?php
    echo nl2br("Welcome\r\nThis is my HTML document", false);
?>

产量

Welcome<br>
This is my HTML document

代替$ order和str_replace位,只需尝试$text = nl2br($t);

暂无
暂无

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

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