I would like to add html tag to string of HTML in PHP, for example:
<h2><b>Hello World</b></h2>
<p>First</p>
Second
<p>Third</p>
Second is not wrapped with any html element, so system will add p tag into it, expected result:
<h2><b>Hello World</b></h2>
<p>First</p>
<p>Second</p>
<p>Third</p>
Tried with PHP Simple HTML DOM Parser but have no clue how to deal with it, here is my example of idea:
function htmlParser($html)
{
foreach ($html->childNodes() as $node) {
if ($node->childNodes()) {
htmlParser($node);
}
// Ideally: add p tag to node innertext if it does not wrapped with any tag
}
return $html;
}
But childNode will not loop into Second because it has no element wrapped inside, and regex is not recommended to deal with html tag, any idea on it?
Much appreciate, thanks.
This was a cool question because it promoted thought about the DoM.
I raised a question How do HTML Parsers process untagged text which was commented generously by @sideshowbarker, which made me think, and improved my knowledge of the DoM, especially about text nodes.
Below is a DoM based way of finding candidate text nodes and padding them with 'p' tags. There are lots of text nodes that we should leave alone, like the spaces, carriage returns and line feeds we use for formatting (which an "uglifier" may strip out).
nodeTest.html contains this.
and the output is this.... I did not bother echoing the outer tags. Notice that comments and formatting are properly treated.
Obviously you need to traverse the DoM and repeat the search/replace at each element node if you wish to make the thing more general. We are only stopping at the Body node in this example and processing each direct child node.
I'm not 100% sure the code is the most efficient possible and I may think some more on that and update if I find a better way.
You can try Simple HTML Dom Parser
Used a stupid way to solve this problem, here is my code:
Hope there is other elegant way rather than this, thanks.