/ Published in: PHP
Transform text (eg. from a WYSIWYG) into nicely formatted HTML paragraphs. (Credits: Ludo Magnocavallo's LightPress).
[this is a solid starting point - but a lot of HTML elements are missing]
[this is a solid starting point - but a lot of HTML elements are missing]
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
function linebreaker(&$s) { $buffer = ''; $inside = false; $c = $s[$i]; switch ($c) { case '<': $inside = true; $buffer .= $c; break; case '>': $inside = false; $buffer .= $c; break; case "\n": $buffer .= ($inside ? "\n" : "<br />\n"); break; default: $buffer .= $c; } } return $buffer; } function ¶grapher(&$s) { return($s); // already formatted // clean up bare & // code should be inside pre to be preformatted, let's leave it here for now anyway $block_tags = 'object|pre|p|dl|div|noscript|script|blockquote|form|table|td|th|ins|fieldset|address|h1|h2|h3|h4|h5|h6|ul|ol|li|code'; $r = '@(?: # match paragraph mark ((?:\n\s*){2,}) | # match block open tag (< # save tag (' . $block_tags . ') # save tag name [^>]*>) | # match block close tag (</\s*(' . $block_tags . ')\s*>) )@smix'; if ($matches == 0) { $buffer = "<p>" . linebreaker($s) . "</p>"; return $buffer; } else { $buffer = ''; $pre = false; $last_offset = 0; $tag = null; $tag_content = ''; $reset_tag = null; foreach ($m as $match) { // grab the content from the latest match offset up to the current one $offset = $match[0][1]; if ($convert) { $slice = linebreaker($slice); } // now fill the buffer $buffer .= $convert ? "<p>$slice</p>\n" : "$slice"; // set the current tag context case 2: # paragraph mark $buffer .= $pre ? "\n\n" : ''; break; case 4: # block open tag $tags[] = $tag; if ($tag == 'pre' || $tag == 'script') $pre = true; $buffer .= $match[0][0] . ($pre ? '' : "\n"); break; case 6: # block close tag if ($tag == 'pre' || $tag == 'script') $pre = false; $buffer .= $match[0][0] . ($pre ? '' : "\n"); if ($tag == 'pre') $pre = false; if ($tlen > 0) $tag = $tags[$tlen - 1]; else $tag = $pre = null; break; } } if ($pre) { // unlikely, but does not hurt to check $buffer .= $tail; } else { $buffer .= '<p>' . linebreaker($tail) . '</p>'; } } return $buffer; }
URL: http://lightpress-de.googlecode.com/svn/trunk/lightpress/classes/Frontend.php