我的原始HTML看起来像这样:
<h1>Page Title</h1>
<h2>Title of segment one</h2>
<img src="img.jpg" alt="An image of segment one" />
<p>Paragraph one of segment one</p>
<h2>Title of segment two</h2>
<p>Here is a list of blabla of segment two</p>
<ul>
<li>List item of segment two</li>
<li>Second list item of segment two</li>
</ul>
现在,使用PHP(而不是jQuery),我想要更改它,如下所示:
<h1>Page Title</h1>
<div class="pane">
<h2>Title of segment one</h2>
<img src="img.jpg" alt="An image of segment one" />
<p>Paragraph one of segment one</p>
</div>
<div class="pane">
<h2>Title of segment two</h2>
<p>Here is a list of blabla of segment two</p>
<ul>
<li>List item of segment two</li>
<li>Second list item of segment two</li>
</ul>
</div>
因此,基本上,我希望用
<h2></h2>
将所有HTML包裹在<div class="pane" />
标记集之间。上面的HTML已经允许我使用jQuery创建一个手风琴,这很好,但是我想进一步介绍一下:我希望创建一个所有受影响的
<h2></h2>
集的ul,如下所示:<ul class="tabs">
<li><a href="#">Title of segment one</a></li>
<li><a href="#">Title of segment two</a></li>
</ul>
请注意,我正在使用jQuery工具选项卡来实现此系统的JavaScript部分,并且不需要.tabs的href指向其特定的h2副本。
我的第一个猜测是使用正则表达式,但我也看到有些人在谈论DOM Document
jQuery中存在两个解决此问题的方法,但是我确实需要一个等效的PHP:
https://stackoverflow.com/questions/7968303/wrapping-a-series-of-elements-between-two-h2-tags-with-jquery
Automatically generate nested table of contents based on heading tags
有人可以请我帮忙吗?
最佳答案
DOMDocument可以帮助您。我之前也回答过类似的问题:
using regex to wrap images in tags
更新资料
完整的代码示例包括:
$d = new DOMDocument;
libxml_use_internal_errors(true);
$d->loadHTML($html);
libxml_clear_errors();
$segments = array(); $pane = null;
foreach ($d->getElementsByTagName('h2') as $h2) {
// first collect all nodes
$pane_nodes = array($h2);
// iterate until another h2 or no more siblings
for ($next = $h2->nextSibling; $next && $next->nodeName != 'h2'; $next = $next->nextSibling) {
$pane_nodes[] = $next;
}
// create the wrapper node
$pane = $d->createElement('div');
$pane->setAttribute('class', 'pane');
// replace the h2 with the new pane
$h2->parentNode->replaceChild($pane, $h2);
// and move all nodes into the newly created pane
foreach ($pane_nodes as $node) {
$pane->appendChild($node);
}
// keep title of the original h2
$segments[] = $h2->nodeValue;
}
// make sure we have segments (pane is the last inserted pane in the dom)
if ($segments && $pane) {
$ul = $d->createElement('ul');
foreach ($segments as $title) {
$li = $d->createElement('li');
$a = $d->createElement('a', $title);
$a->setAttribute('href', '#');
$li->appendChild($a);
$ul->appendChild($li);
}
// add as sibling of last pane added
$pane->parentNode->appendChild($ul);
}
echo $d->saveHTML();