使用regex从HTML表中提取特定值

时间:2014-04-15 16:31:58

标签: php html regex preg-match preg-match-all

我有一个包含此表格行的html文件:

<tr> 
<td class="color21 right" style="font-size:12px; line-height:1.2;">&nbsp;Location</td>
<td class="color21" style="font-size:12px;">10</td>
<td class="color21" style="font-size:12px;"><img src="../../icons/9.gif" alt="Type" />     </td>
<td class="color21" style="font-size:12px;">3</td>
<td class="color21" style="font-size:12px;">7</td>
<td class="color21" style="font-size:12px;"><img src="../../icons/11.gif" alt="Type" />    </td>
<td class="color21" style="font-size:12px;">3</td>
<td class="color21" style="font-size:12px;">10</td>
<td class="color21" style="font-size:12px;"><img src="../../icons/9.gif" alt="Type" />    </td>
</tr>

我正在使用file_get_contents检索文件内容。

如何使用preg_match,preg_match_all?

提取所有TD值

2 个答案:

答案 0 :(得分:1)

想想你是否真的想要一个正则表达式来解析html

但你可以用这个:

<td.+?>(.+?)</td>

第一组将包含<td>

的值

答案 1 :(得分:1)

使用DomParser解析html内容正则表达式在这种情况下不可靠。

    $str=file_get_contents('read.txt');
    $dom = new domDocument;
    $dom->loadHTML($str);
    $tr = $dom->getElementsByTagName('td');
    foreach($tr as $td)
  {
    if(!empty($td->nodeValue)){
        echo $td->nodeValue."\n";
    }else{
        $images=$td->getElementsByTagName('img');
        foreach($images as $image){
            echo $image->getAttribute('src')." ";
            echo $image->getAttribute('alt');
        }
    }