Analysis on line feed usage of the PHP function nl2br () and the custom function nl22p (), nl2brnl22p
This article describes the use of nl-2br () and nl2p () for PHP functions. We will share this with you for your reference. The details are as follows:
Scenario
In many cases, we simply use textarea to get users' long input without using an editor. The line feed entered by the user is input into the database in the form of "\ n". Sometimes there is no line feed during the output, and a large piece of text comes out directly. In this case, you can wrap the text according to \ n in the library. PHP has its own function nl2br (). We can also customize the function nl2p ().
Let's take a look at the nl2br () function.
Definition and usage
The nl2br () function inserts an HTML Line Break (<br/>) before each new line (\ n) in the string ).
A simple example:
<?php$str = "Welcome to www.jb51.net";echo nl2br($str);?>
The HTML code of the running result:
Welcome to <br />www.jb51.net
Nl2p
Nl2br has a disadvantage. For example, it is troublesome to use CSS to indent paragraphs. At this time, nl2p is required. Replace the br line feed with the paragraph p line feed, which is simpler to directly replace:
<?phpfunction nl2p($text) { return "<p>" . str_replace("\n", "</p><p>", $text) . "</p>";}?>
For more detailed functions, try:
/** * 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>';}