donglianglu8136 2015-12-10 20:41
浏览 96
已采纳

如何通过preg_match_all获取来自同一对象的所有匹配? [重复]

This question already has an answer here:

I have a table:

<table class="table_class" >
    <tr>
        <td>key</td>
        <td>value</td>
    </tr>
</table>

The table may have any count of <tr>

I have regexp:

<table class="table_class">(<tr.*?><td>(.*?)</td><td>(.*?)</td></tr>){1,}</table>

But matches array contains only last match.

Just (<tr.*?><td>(.*?)</td><td>(.*?)</td></tr>) I can not do, because other table will may be.

Before apply preg_match_all I delete whitespaces. How do this? Thanks!

UPD: example with a few tables

<table>
    <tr>
        <td>key</td>
        <td>value</td>
    </tr>
</table>
<table class="table_class" >
    <tr>
        <td>key</td>
        <td>value</td>
    </tr>
</table>

yet, I will want to know why my regexp match only last <tr>))

</div>
  • 写回答

1条回答 默认 最新

  • dry9192 2015-12-10 20:51
    关注

    Now usually I'm first to say it's fine to use regexps to extract data from HTML occasionally, as it's oft just faster and more efficient to do so than using a real parser. This is not one of those cases as the structure of the HTML is more than relevant.

    Instead consider something like this:

    $doc = DOMDocument::loadHTML(<<<HTML
    <table class="table_class" >
        <tr><td>key1</td><td>value1</td></tr>
        <tr><td>key2</td><td>value2</td></tr>
        <tr><td>key3</td><td>value3</td></tr>
        <tr><td>key4</td><td>value4</td></tr>
    </table>
    HTML
    );
    foreach($doc->getElementsByTagName('tr') as $row) { 
      foreach($row->getElementsByTagName('td') as $cell)
        var_dump($cell->nodeValue);
    }
    

    See it in action here.

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

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)