在每个H2和H3之前添加元素

时间:2014-03-29 19:19:34

标签: php domdocument

我有以下HTML代码:

Some text
<h2>More text</h2>
<h2>Another h2</h2>

在每个H2元素之前,我想添加一个链接(<a>)。我已经在DOMdocument上苦苦挣扎了一段时间,但我不能这样做。

我一直在努力解决很多变种问题。有些崩溃,而其他人则在文档的开头或结尾添加链接,或者在<H2>元素中添加链接。他们都没有在<h2>之前添加它。

$text = 'Some text<h2>More text</h2><h2>Another h2</h2>';
$dom = new domDocument('1.0', 'utf-8'); 
$dom->loadHTML($text); 
$dom->preserveWhiteSpace = false; 
$el = $dom->createElement('a');
$x = $dom->getElementsByTagName('h2')->item(0);
$dom->insertBefore($el,$x);

1 个答案:

答案 0 :(得分:3)

您需要在insertBefore上使用$tag->parentNode。您还必须为每个插入创建一个新元素(或者它将移动旧元素)。

<?php
$text = 'Some text<h2>More text</h2><h2>Another h2</h2>';
$dom = new domDocument('1.0', 'utf-8'); 
$dom->loadHTML($text); 
$dom->preserveWhiteSpace = false; 

foreach ($dom->getElementsByTagName('h2') as $tag) {
    $el = $dom->createElement('a');
    $el->setAttribute('class', 'foo');
    $el->setAttribute('href', '#');

    $tag->parentNode->insertBefore($el, $tag);
}

foreach ($dom->getElementsByTagName('h3') as $tag) {
    $el = $dom->createElement('a');
    $el->setAttribute('class', 'foo');
    $el->setAttribute('href', '#');

    $tag->parentNode->insertBefore($el, $tag);
}

var_dump($dom->saveHTML());

<强>输出

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
    <body>
        <p>Some text</p>

        <a class="foo" href="#"></a>
        <h2>More text</h2>

        <a class="foo" href="#"></a>
        <h2>Another h2</h2>
    </body>
</html>

DEMO

相关问题