用PHP包装带有div的HTML段(并从HTML标签生成目录)

问题描述 投票:2回答:3

我的原始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><div class="pane" />标签集之间包装所有HTML上面的HTML已经允许我用jQuery创建一个手风琴,这很好,但我想进一步:

我希望创建一个受影响的所有<h2></h2>sets的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等价物:

有人可以请几乎帮助我吗?

php regex dom
3个回答
3
投票

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();

2
投票

使用PHP DOM函数执行此任务。


1
投票

..一个很好的PHP HTML解析器是你需要的。 This一个很好。它的PHP等同于jquery。

© www.soinside.com 2019 - 2024. All rights reserved.