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

标签 php html wordpress domdocument

我需要替换 WordPress 页面上 div 部分中的可变数量的连续段落,该部分仅包含这一个 div部分。我想在服务器端执行此操作。我认为这可以通过 the_content() 钩子(Hook)和 DomDocument 类来完成,但我不知道如何做到这一点。您可以在下面看到 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();

关于php - 使用 PHP DOMDocument 将某些元素替换为自定义内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70644260/

相关文章:

html - Wordpress 菜单项视频灯箱

php - facebook graph api 没有返回足够的新闻提要详细信息来重建您在 facebook 主页上看到的内容

php - 如何限制 Laravel Fortify 中的忘记密码请求?

javascript - HTML5 <Dialog> 只适用于 chrome?

wordpress - Wordpress-图像未显示在媒体库中

javascript - 构建动态且响应迅速的图像拼贴

php - 简单的mysql插入错误,查询未执行且数据未插入表中

php - 通过特定属性的值在数组中搜索对象的最有效方法

javascript - 如何使用<td>值进行jquery计算代替&lt;input type ="number">

javascript - 滚动条应该在没有 setInterval() 的底部