doupi3874 2015-03-26 17:39
浏览 90
已采纳

用class删除div并保留所有其他html

My html content:

$content = <div class="class-name some-other-class">
<p>ack</p>
</div>

Goal: Remove div with class="class-name so that I'm left with:

<p>ack</p>

I know strip_tags($content, '<p>'); would do the job in this instance but I want to be able to target the divs with a certain class and preserve other divs etc.

And I'm aware that you shouldn't pass html through regex - So whats the best way/proper way to achieving this.

  • 写回答

2条回答 默认 最新

  • dptx8888 2015-03-26 17:46
    关注
    $doc = new DOMDocument();
    libxml_use_internal_errors(true);
    $doc->loadHTML($content); // loads your HTML
    $xpath = new DOMXPath($doc);
    // returns a list of all links with class containing class-name
    $nlist = $xpath->query("div[contains(@class, 'class-name')]");
    
    // Remove the nodes from the xpath query
    foreach($nlist as $node) {
       $node->parentNode->removeChild($node);
    }
    
    echo $doc->saveHtml();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题