【问题标题】:How can I extract the content of a <tr> tag in PHP?如何在 PHP 中提取 <tr> 标签的内容?
【发布时间】:2012-12-02 01:35:33
【问题描述】:

我是正则表达式的新手。我想问一下这个html标签的正确组合是什么:

   <tr class="calendar_row" data-eventid="39654">
      <td class="alt1 eventDate smallfont" align="center"/></td>
      <td class="alt1 smallfont" align="center">3:34am</td>
      <td class="alt1 smallfont" align="center">CNY</td>
   </tr>

我正在使用这个:

   $html = website html from a url
   $match = array();

   $pattern = "/(<tr.*?\data-eventid\>.*?<\/tr>)/ims";
   preg_match_all($pattern, $html, $match);

但它不起作用:| 我只想选择该 tr 元素的所有内容..

最好的问候。

【问题讨论】:

    标签: php html regex html-parsing


    【解决方案1】:

    使用 DOMDocument

    你不应该在这样的事情上使用正则表达式;而是从您的标记中创建一个DOMDocument,然后从该特定元素中选择子元素。例如,以下将为我们提供标记中每个 &lt;td&gt; 标记的集体 html:

    // Our HTML will eventually go here
    $innerHTML = "";
    
    // Create a new DOMDocument based on our HTML
    $document = new DOMDocument;
    $document->loadHTML($html);
    
    // Get a NodeList of all <td> Elements
    $cells = $document->getElementsByTagName("td");
    
    // Cycle over each <td>, adding its HTML to $innerHTML
    foreach ($cells as $cell) {
        $innerHTML .= $document->saveHTML($cell);
    }
    
    // Output our glorious HTML
    echo $innerHTML;
    

    正则表达式

    如果您真的想使用preg_match 获取tr 标记之间的内容,则以下方法应该可以:

    // Our pattern for capturing all that is between <tr> and </tr>
    $pattern = "/<tr[^>]*>(.*)<\/tr>/s";
    
    // If a match is found, store the results in $match
    if (preg_match($pattern, $html, $match)) {
        // Show the captured value
        echo $match[1];
    }
    

    结果如下:

    <td class="alt1 eventDate smallfont" align="center"></td>
    <td class="alt1 smallfont" align="center">3:34am</td>
    <td class="alt1 smallfont" align="center">CNY</td>
    

    【讨论】:

    • @Vainglory07 我明白了;但是如果你想解析 HTML,你不应该使用正则表达式,而是通过更安全的方式将其作为文档对象处理。
    • :(我不知道..我很抱歉..我只是在研究过去项目中的现有功能..
    • @Vainglory07 我已经更新了分享这两种方法的答案。很高兴我们能对您有所帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 2015-06-10
    • 2011-08-26
    • 2014-06-25
    • 1970-01-01
    相关资源
    最近更新 更多