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

如何通过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 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state