2

私の元の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>

ここで、(jQueryではなく)PHPを使用して、次のように変更します。

<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>

このシステムのJavaScript部分を実装するためにjQueryツールタブを使用していることに注意してください。.tabsのhrefが特定のh2対応物を指している必要はありません。

私の最初の推測は正規表現を使用することですが、DOMドキュメントについて話している人もいます。

jQueryのこの問題には2つの解決策がありますが、PHPに相当するものが本当に必要です。

誰かが実際に私を助けてくれませんか?

4

3 に答える 3

3

DOMDocument はそれを助けることができます。私は以前に同様の質問に答えました:

正規表現を使用して画像をタグでラップする

アップデート

完全なコード サンプルが含まれています:

$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();
于 2012-05-21T10:21:35.530 に答える
2

このタスクを実行するには、 PHPDOM関数を使用します。

于 2012-05-21T10:20:22.350 に答える
1

..素敵な PHP html パーサーが必要です。 これは良いです。jquery に相当する PHP です。

于 2012-05-21T10:36:14.650 に答える