dtp0760 2011-02-04 23:06
浏览 42
已采纳

使用DOM PHP替换父标记内的标记

Here is what I got:

<div id="list">
<ol>
  <li>Ordered list 1</li>
  <li>Ordered list 2</li>
  <ul><li>Unordered list inside ol ul</li></ul>
  <ol><li>Ordered list inside ol ol</li></ol>
</ol>

<ul>
  <li>Unordered list</li>
  <ol><li>Ordered list inside ul</li></ol>
</ul>

<ol>
  <li>Ordered list 1</li>
  <ol><li>Ordered list inside ol ol</li></ol>
</ol>
</div>

I need somehow replace LI tags only inside div id="list" -> OL tags I need so that it replaces only LI tags only within the first OL tags and not UL or the once inside OL -> OL tags

I tried using preg_replace_callback but it only replaces all LI tags inside id="list" and from what i figured it will be over my head to limit replacement only with first ol tags and not the rest, so I been suggested to try out PHP DOM since it should be as easy as div id="list" -> OL

I would appreciate if someone got me started with the code, maybe with something as replacing all LI tags with in the first OL tag within the whole content.

  • 写回答

1条回答 默认 最新

  • duanhuang4306 2011-02-04 23:23
    关注

    You shouldn't do this with regex. It's a very bad way to parse (HT|X)ML. Use a genuine parser instead. Here's an example using PHP's DOMDocument class and the related DOMXPath:

    <?php
    
    $doc = new DomDocument(); 
    $doc->loadXML('your HTML');
    $xpath = new DOMXPath($doc);  
    
    // get li elements in the first ol in the div whose id is list
    $nodes = $xpath->query('//div[@id="list"]/ol[1]/li');
    
    // change li elements to <li class='list'><div class='inline'>#####</div></li>
    foreach ($nodes as $node) {
        $node->setAttribute('class', 'list');
        $number = $node->firstChild;
        $div = $doc->createElement('div');
        $div->setAttribute('class', 'inline');
        $div->appendChild($number);
        $node->appendChild($div);
    }
    
    // get the new HTML
    $html = $doc->saveHTML();
    

    NB also that you'll need to fix your ol and ul closing tags, which are currently unclosed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 阿里云python代码求解
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路