doudu4282 2016-08-22 09:58
浏览 45
已采纳

如何在PHP中将HTML字符串拆分为块? [重复]

This question already has an answer here:

I would like to split a string efficiently into different sub strings like this :

  <li><a href="">One</a></li><li><a href>Two</a></li><li><a href>Three</a></li>.....<li><a herf>Last</a></li>

I would like to split this string in 3 parts and put each string in a variable.

The first variable $first should contain the first li (<li>One</li>) The second variable $second should contain the rest expect the last (<li>Two</li><li>Three</li>.....) The third variable $third should contain the last li (<li>Last</li>)

Anyone can help ?

</div>
  • 写回答

3条回答 默认 最新

  • douyong5825 2016-08-22 10:19
    关注

    Should work:

    <?php 
    
    $dom = new DOMDocument;
    $dom->loadHTML('<li><a href="#">One</a></li><li><a href="#">Two</a></li><li><a href="#">Three</a></li><li><a href="#">Last</a></li>');
    $liTags = $dom->getElementsByTagName('li');
    
    $chunks = array();
    foreach ($liTags as $li) {
        $chunks[] = '<li>'.strip_tags($li->nodeValue).'</li>';
    }
    
    list($first,$second,$third) = array(
       array_slice($chunks,0,1),
       array_slice($chunks,1,count($chunks)-2),
       array_slice($chunks,-1),    
    );
    
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 vhdl+MODELSIM
  • ¥20 simulink中怎么使用solve函数?
  • ¥30 dspbuilder中使用signalcompiler时报错Error during compilation: Fitter failed,求解决办法
  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题