Wednesday, March 11, 2009

Semantic nl2br()

Here's a little PHP function that I wrote to replace nl2br() when it's actually a paragraph break that's required. It creates more semanic code for textarea fields being displayed from a mysql database. It replaces one \n with <br />but if there are 2 together, they are replaced with </p><p>. You initiate the first paragraph and end the last paragraph when you call the function.

Here's the function:
// define function
function lineBreaks($lines) {
// insert break tags
$lines = nl2br($lines);

// create an array of all the possible multiple break tags
$breaks = array("<br /><br />", "<br />\r\n<br />", "<br />\n<br />", "<br />\r<br />");
$paragraphs = "</p><p>";

// replace multiple break tags with paragraph tags
$lines = str_replace($breaks, $paragraphs, $lines);
return $lines;
}


Here's how you call it:
// $row['details'] is the name of the field. It could be anything.
echo "<p>".lineBreaks($row['details'])."</p>\n";

No comments:

Post a Comment

If you want to include code in your comment, use this function first. It's provided by Bogdan Valentin - Thanks Bogdan!