douliao8402 2012-08-16 13:34
浏览 28

在PHP中的正则表达式,采取HTML [重复]

Possible Duplicate:
RegEx match open tags except XHTML self-contained tags
How to parse and process HTML with PHP?

i need help. I have HTML, and i need regular expression which give me table. only one table. because after this table goes another tables. example html:

<table class="results" cellspacing="1" cellpadding="0" border="0" width="100%" align="left">
    <tr><td>text</td></tr>
</table>
<!-style>
tr.bg_selected{}
tr.bg_selected td, tr.bg_checked td { background-color:#ffe9bc !important;}
</style>**AND ANOTHER TABLE**

its my regular. there i get all tables after this table.

$regular = "/<table class=\"results\" cellspacing=\"(\d+)\" cellpadding=\"(\d+)\" border=\"(\d+)\" (.*)>(.*)<\/table>
(.*)<\/style>/s";
    preg_match_all($regular,$str, $matches2, PREG_PATTERN_ORDER);
  • 写回答

1条回答 默认 最新

  • dongqiang4819 2012-08-16 14:18
    关注

    Some people have pointed out in the comments that you "can't parse HTML in regex". This isn't entirely accurate; it can be done.

    However, it's difficult and error prone, and at the end of it you get a bit of a messy structure to work with.

    I would therefore strongly recommend using PHP's built in HTML parser instead. It's very simple to use:

    $doc = new DOMDocument();
    $doc->loadHTML($htmlCode);
    

    You can then work with the resulting object to extract the data you need.

    $tables = $dom->getElementsByTagName('table');
    foreach ($tables as $table){
        $cells = $table->getElementsByTagName('td');
        foreach ($cells as $cell){
            echo $cell->nodeValue;
        }
    }
    

    See the PHP manual for more info: http://php.net/manual/en/book.dom.php

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?