欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP函數(shù)nl2br()與自定義函數(shù)nl2p()換行用法分析

 更新時(shí)間:2016年04月02日 10:55:06   作者:nowamagic  
這篇文章主要介紹了PHP函數(shù)nl2br()與自定義函數(shù)nl2p()換行用法,結(jié)合實(shí)例形式分析PHP函數(shù)nl2br實(shí)現(xiàn)換行功能的優(yōu)缺點(diǎn)及自定義函數(shù)nl2p換行功能的使用技巧,需要的朋友可以參考下

本文實(shí)例講述了PHP函數(shù)nl2br()與自定義函數(shù)nl2p()換行用法。分享給大家供大家參考,具體如下:

使用情景

很多場(chǎng)合我們只是簡(jiǎn)單用textarea獲取用戶的長(zhǎng)篇輸入,而沒有用編輯器。用戶輸入的換行以“\n”的方式入庫,輸出的時(shí)候有時(shí)候會(huì)沒有換行,一大片文字直接出來了。這個(gè)時(shí)候可以根據(jù)庫里的“\n”給文字換行。PHP有自帶的函數(shù)nl2br(),我們也可以自定義函數(shù)nl2p()。

先來看看nl2br() 函數(shù)吧。

定義和用法

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

一個(gè)簡(jiǎn)單的例子:

<?php
$str = "Welcome to 
www.dbjr.com.cn";
echo nl2br($str);
?>

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

Welcome to <br />
www.dbjr.com.cn

nl2p

nl2br 有個(gè)缺點(diǎn),比如要用CSS做到段落縮進(jìn)就比較麻煩,這個(gè)時(shí)候就需要 nl2p 了。將br換行換成段落p換行,比較簡(jiǎn)單是直接替換:

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

比較詳細(xì)的函數(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相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP基本語法入門教程》、《php操作office文檔技巧總結(jié)(包括word,excel,access,ppt)》、《php日期與時(shí)間用法總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總

希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論