Created
September 2, 2014 11:05
-
-
Save JanTvrdik/74080d5178f3b113efd9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function createParagraphs($html) | |
{ | |
$html = '<meta http-equiv="content-type" content="text/html;charset=utf-8"><body>' . $html; | |
$document = new DOMDocument(); | |
$document->loadHTML($html); | |
$body = $document->getElementsByTagName('body')->item(0); | |
$inlineTags = ['a', 'b', 'del', 'em', 'i', 'img', 'ins', 'small', 'span', 'strong']; | |
$create = TRUE; | |
for ($node = $body->firstChild; $node; $node = $next) { | |
$next = $node->nextSibling; | |
if ($node instanceof DOMText) { | |
$children = explode("\n", $node->nodeValue); | |
$body->removeChild($node); | |
$node = $next; | |
} elseif ($node instanceof DOMElement && in_array($node->nodeName, $inlineTags, TRUE)) { | |
$children = [$node]; | |
} else { | |
$children = []; | |
$create = TRUE; | |
} | |
foreach ($children as $child) { | |
if ($child !== '') { | |
if ($create) { | |
$p = $body->insertBefore($document->createElement('p'), $node); | |
$create = FALSE; | |
} | |
$p->appendChild(is_string($child) ? $document->createTextNode($child) : $child); | |
} else { | |
$create = TRUE; | |
} | |
} | |
} | |
return substr($document->saveHTML($body), 7, -8); // strip "<body>\n ... \n</body>" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment