使用 PHP DOMDocument 将一些元素替换为自定义内容

Replace some elements with a custom content using PHP DOMDocument

我需要在 Wordpress 页面的 div 部分中替换可变数量的 连续段落 ,该部分仅包含这一 div 部分.我想在服务器端执行此操作。我认为这可以通过 the_content() 挂钩和 DomDocument class 来完成,但我不知道该怎么做。您可以在下面看到 div 部分结构。我需要替换的段落在最后一个标题和最后一段之间(因此标题和最后一段保持不变)。我将不胜感激任何帮助。

<div id="text-document">
    <h2>a title</h2>
    <p>some content</p>
    <!-- other paragraphs here -->

    <!-- some other DIVs, titles and paragraphs here -->

    <h2>the last title</h2>

    <!-- some paragraphs here -->

    <p>the last paragraph</p>
</div>

DomDocument/Wordpress部分:

add_filter( 'the_content', function( $content ) {
    $content = mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' );
    $dom = new DOMDocument( '1.0', 'UTF-8' );
    @$dom->loadHTML( $content );

    //the missing part

    $content = $dom->saveHTML( $dom );

    return $content;
} );

如果我对你的理解是正确的,按照这些思路至少应该让你更接近你想去的地方:

$xpath = new DOMXPath($dom);

$targets = $xpath->query('//h2[last()]/following-sibling::p[not(position()=last())]');

foreach($targets as $target){
        $target->parentNode->removeChild($target);}

$destination = $xpath->query('//p[last()]');
$template = $dom->createDocumentFragment();
$template->appendXML('<p>I am new here</p>');
$destination[0]->parentNode->insertBefore($template, $destination[0]);
echo $dom->saveHTML();