Skip to content

Instantly share code, notes, and snippets.

@JanTvrdik
Created September 2, 2014 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JanTvrdik/74080d5178f3b113efd9 to your computer and use it in GitHub Desktop.
Save JanTvrdik/74080d5178f3b113efd9 to your computer and use it in GitHub Desktop.
<?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