Reputation: 177
I have some code which follows the order as below -
<h1>Title</h1>
<p>Text here</p>
<ul><li>maybe a list</li></ul>
<h1>Title 1</h1>
<p>More text here</p>
<h2>maybe a h2 somewhere</h2>
I am wondering if, with using PHP and/or jQuery, there is any way to wrap each h1 tag with a span tag and everything up until the next h1 tag (so the p, ul or h2 tag) in another span tag so I end up with something as below -
<span class="header"><h1>Title</h1></span>
<span class="content">
<p>Text here</p>
<ul><li>maybe a list</li></ul>
</span>
<span class="header"><h1>Title 1</h1></span>
<span class="content">
<p>More text here</p>
<h2>maybe a h2 somewhere</h2>
</span>
Any help would be greatly appreciated.
EDIT - Should have added before that the whole text comes from a database as one row of data.
Upvotes: 0
Views: 414
Reputation: 11
I've made a similar code with python and beautiful soup and it's quite easy if you traverse your html with a tree.
you could use PHP Simple HTML DOM Parser
Parse the html :
$html = str_get_html('<h1>Title</h1><p>Text here</p><ul><li>maybe a list</li></ul><h1>Title 1</h1><p>More text here</p><h2>maybe a h2 somewhere</h2>');
then find all the h1 tags :
foreach($html->find('h1') as $element)
Wrap it with your span (or div maybe ?) in a new tag, and find the next h1 as you add all (and delete from the tree) the sibling that are not h1 into this new tag.
$element->next_sibling()
...
Then replace the original h1 by the new tags you have created.
Hope this helps
Upvotes: 1