This article mainly introduces the PHP function nl2br () and the Custom Function nl2p () line usage, combined with the example form to analyze PHP functions nl2br The advantages and disadvantages of implementing line wrapping function, and the use of custom functions nl2p line-wrapping function, the need for friends can refer to the next
Usage Scenarios
On many occasions we simply use textarea to get a lengthy input from a user without using an editor. User input line to the "\ n" way into the storage, the output sometimes will not be wrapped, a large text directly out. This time can be changed according to the "\ n" in the library to the text line. PHP has its own function nl2br (), and 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);? >
HTML code to run the result:
Welcome to <br/>www.jb51.net
nl2p
NL2BR has a disadvantage, such as to use CSS to achieve paragraph indentation is more troublesome, this time need to nl2p. Replace the BR line with the paragraph p line Wrap, the simpler is the direct substitution:
<?phpfunction nl2p ($text) {return <p>. Str_replace ("\ n", "</p><p>", $text). "</p>";}? >
For more detailed functions, you can try the following:
/** * Returns string with newline formatting converted into HTML paragraphs. * * @param string $string string to is formatted. * @param boolean $line _breaks when True, Single-line Line-breaks'll be a converted to HTML break tags. * @param boolean $xml When True, an XML self-closing tag would 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 this 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 ("& Lt;/p>\n<p> ", ' <br '. ($xml = = true? ' /' : '').' > '), Trim ($string)). ' </p> '; else return ' <p> '. Preg_replace ("/([\n]{1,})/I", "</p>\n<p>", Trim ($string)). ' </p> ';}
Summary: The above is the entire content of this article, I hope to be able to help you learn.