簡體   English   中英

如何在PHP中提取<tr>標記的內容?

[英]How can I extract the content of a <tr> tag in PHP?

我是正則表達式的新手。 我想問一下這個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元素的所有內容..

最好的祝福。

使用DOMDocument

你不應該在這樣的事情上使用正則表達式; 而是從您的標記創建一個DOMDocument ,然后從該特定元素中選擇子元素。 例如,以下內容將為您提供標記中每個<td>標記的集合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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM