簡體   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