PHP Function to Convert Multiline String to HTML Paragraphs
PHP Function Code to Take Multiline String, Remove Empty Lines, Surround Remaining Lines with HTML Paragraph Tags <p> <\p>
Home
Short:
/* ---------------------------------------------------------- function takes multiple text [$text], removes empty lines and surround each remaining line with html paragraph tags
---------------------------------------------------------- */ function lineBreakToParagraphs($text, $numSpacesPadLeft = 0) { $spaces = str_repeat(" ", $numSpacesPadLeft); // normalize line breaks for both windows and unix environments $text = str_replace(array("\r\n", "\r"), "\n", $text); $arr = explode("\n", $text); // Remove empty strings from the array $arr = array_filter($arr, function($value) { return strlen(trim($value)) > 0; }); // if empty dont bother surround with
tags if( count($arr) == 0) { return ""; } // surround each arr elem with paragraph tags and join as string $out = $spaces . "
" . implode("
\n" . $spaces . "
", $arr) . "
"; return $out; }
source code home