@ 2013-08-13T16:53:47Z <?php
/**
* DOM xpath to find #text nodes and wrap in paragraph tag
* @link http://stackoverflow.com/q/15552560/367456
*/
$html = '<div>
This text should be wrapped in a p tag.
</div>
This also should be wrapped.
<b>And</b> this.';
$paragraphSequence = "\n\n";
$paragraphSequenceLength = 2;
$paragraphComment = 'break';
/**
* @param DOMNode $element
*
* @link http://php.net/book.dom
* @return string
*/
$innerHTML = function (DOMNode $element)
{
$innerHTML = "";
$children = $element->childNodes;
foreach ($children as $child)
{
$innerHTML .= $element->ownerDocument->saveHTML($child);
}
return $innerHTML;
};
/**
* @param $html
*
* @return DOMElement
* @throws InvalidArgumentException
*/
$loadHTMLFragment = function ($html)
{
$doc = new DOMDocument();
$doc->loadHTML("<body>$html");
$anchor = $doc->getElementsByTagName('body')->item(0);
if (!$anchor)
{
throw new InvalidArgumentException('Unable to load HTML fragment.');
}
return $anchor;
};
$insertBreakMarkBefore = function (DOMText $node, $paragraphSequenceBefore = FALSE) use ($paragraphSequence, $paragraphComment)
{
if ($paragraphSequenceBefore)
{
$node->parentNode->insertBefore($node->ownerDocument->createTextNode($paragraphSequence), $node);
}
$node->parentNode->insertBefore($node->ownerDocument->createComment($paragraphComment), $node);
$node->parentNode->insertBefore($node->ownerDocument->createTextNode($paragraphSequence), $node);
};
$anchor = $loadHTMLFragment($html);
$xp = new DOMXPath($anchor->ownerDocument);
/* @var $result DOMText[] */
$result = $xp->query('(.|./div)/text()', $anchor);
foreach ($result as $i => $node)
{
if ($node->parentNode->tagName == 'div')
{
$insertBreakMarkBefore($node, true);
}
while (FALSE !== $pos = strpos($node->data, $paragraphSequence))
{
$node = $node->splitText($pos + $paragraphSequenceLength);
$insertBreakMarkBefore($node);
}
}
$needle = sprintf('%1$s<!--%2$s-->%1$s', $paragraphSequence, $paragraphComment);
$replace = sprintf("\n<p class=\"%s\">\n", $paragraphComment);
$html = strtr($innerHTML($anchor), array($needle . $needle => $replace, $needle => $replace));
echo "HTML afterwards:\n", $innerHTML($loadHTMLFragment($html));
Enable javascript to submit You have javascript disabled. You will not be able to edit any code.
Output for git.master , git.master_jit , rfc.property-hooks HTML afterwards:
<div>
<p class="break">
This text should be wrapped in a p tag.
</p></div>
<p class="break">
This also should be wrapped.
</p><p class="break">
<b>And</b> this.</p> This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.
Active branches Archived branches Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page
preferences:dark mode live preview
44.84 ms | 401 KiB | 8 Q