in a semantic way class BlockFormat { var $lines = array(); var $paragraph = false; var $block = false; var $newtext = ''; var $blockElements = '(h[1-6]|ol|ul|pre|blockquote|p|dl)'; function init($text) { $text = str_replace("\r", '', $text); $text = explode("\n", trim($text)); $this->lines = $text; } function openBlock($tag) { $this->block = true; $this->newtext.= '<'.$tag.'>'; } function closeBlock($tag) { $this->block = false; $this->newtext.= '\n\n"; } function openParagraph() { $this->paragraph = true; $this->newtext.= "

"; } function closeParagraph() { $this->paragraph = false; $this->newtext.= "

\n\n"; } function append($text) { $this->newtext.= $text; } function Process($text) { $this->init($text); foreach($this->lines as $i=>$line) { $line = trim($line); if (empty($line)) { if ($this->paragraph) { $this->closeParagraph(); } continue; } elseif (preg_match('/<('.$this->blockElements.'[^>]*)>/', $line, $match)) { if ($this->paragraph) { $this->closeParagraph(); } $this->openBlock($match[1]); $line = str_replace($match[0], '', $line); } else { if (!$this->paragraph && !$this->block) { $this->openParagraph(); } } if (preg_match('/<\/'.$this->blockElements.'>/', $line, $match) && $this->block) { $close_block = $match[1]; $line = str_replace($match[0], '', $line); } if ($this->paragraph && !empty($this->lines[$i+1])) { $line.= "
\n"; } if (!empty($line)) $this->append($line); if (isset($close_block)) { $this->closeBlock($close_block); unset($close_block); } } if ($this->paragraph) $this->closeParagraph(); return $this->newtext; } } ?>