溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在PHP中使用nl2br()函數(shù)

發(fā)布時間:2021-04-02 16:26:30 來源:億速云 閱讀:155 作者:Leah 欄目:開發(fā)技術(shù)

如何在PHP中使用nl2br()函數(shù)?針對這個問題,這篇文章詳細介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

定義和用法

nl2br() 函數(shù)在字符串中的每個新行 (\n) 之前插入 HTML 換行符 (<br />)。

一個簡單的例子:

<?php
$str = "Welcome to 
www.jb51.net";
echo nl2br($str);
?>

運行結(jié)果的HTML代碼:

Welcome to <br />
www.jb51.net

nl2p

nl2br 有個缺點,比如要用CSS做到段落縮進就比較麻煩,這個時候就需要 nl2p 了。將br換行換成段落p換行,比較簡單是直接替換:

<?php
function nl2p($text) {
 return "<p>" . str_replace("\n", "</p><p>", $text) . "</p>";
}
?>

比較詳細的函數(shù),可以試下:

/**
 * Returns string with newline formatting converted into HTML paragraphs.
 *
 * @param string $string String to be formatted.
 * @param boolean $line_breaks When true, single-line line-breaks will be converted to HTML break tags.
 * @param boolean $xml When true, an XML self-closing tag will be applied to break tags (<br />).
 * @return string
 */
function nl2p($string, $line_breaks = true, $xml = true)
{
  // Remove existing HTML formatting to avoid double-wrapping things
  $string = str_replace(array('<p>', '</p>', '<br>', '<br />'), '', $string);
  // It is conceivable that people might still want single line-breaks
  // without breaking into a new paragraph.
  if ($line_breaks == true)
    return '<p>'.preg_replace(array("/([\n]{2,})/i", "/([^>])\n([^<])/i"), array("</p>\n<p>", '<br'.($xml == true ? ' /' : '').'>'), trim($string)).'</p>';
  else 
    return '<p>'.preg_replace("/([\n]{1,})/i", "</p>\n<p>", trim($string)).'</p>';
}

關(guān)于如何在PHP中使用nl2br()函數(shù)問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI