Posted By

traeregan on 09/22/09


Tagged

nl2br nl2p


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

vas3k
silentbob84


nl2p - alternative to nl2br


 / Published in: PHP
 

URL: http://www.youngcoders.com/share-php-script/26933-nl2p-alternative-nl2br.html

  1. /**
  2.  * Returns string with newline formatting converted into HTML paragraphs.
  3.  *
  4.  * @author Michael Tomasello <[email protected]>
  5.  * @copyright Copyright (c) 2007, Michael Tomasello
  6.  * @license http://www.opensource.org/licenses/bsd-license.html BSD License
  7.  *
  8.  * @param string $string String to be formatted.
  9.  * @param boolean $line_breaks When true, single-line line-breaks will be converted to HTML break tags.
  10.  * @param boolean $xml When true, an XML self-closing tag will be applied to break tags (<br />).
  11.  * @return string
  12.  */
  13. function nl2p($string, $line_breaks = true, $xml = true)
  14. {
  15. // Remove existing HTML formatting to avoid double-wrapping things
  16. $string = str_replace(array('<p>', '</p>', '<br>', '<br />'), '', $string);
  17.  
  18. // It is conceivable that people might still want single line-breaks
  19. // without breaking into a new paragraph.
  20. if ($line_breaks == true)
  21. return '<p>'.preg_replace(array("/([\n]{2,})/i", "/([^>])\n([^<])/i"), array("</p>\n<p>", '<br'.($xml == true ? ' /' : '').'>'), trim($string)).'</p>';
  22. else
  23. return '<p>'.preg_replace("/([\n]{1,})/i", "</p>\n<p>", trim($string)).'</p>';
  24. }

Report this snippet  

You need to login to post a comment.