【问题标题】:Extract specific values from HTML table using regex使用正则表达式从 HTML 表中提取特定值
【发布时间】:2014-05-30 03:35:24
【问题描述】:

我有一个包含此表行的 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 值?

【问题讨论】:

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


    【解决方案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');
            }
        }
    

    【讨论】:

    • 这对数值很有效,但我还需要 9.gif、11.gif 等图像值...您有什么建议吗?
    • 我很乐意得到整个 img 字符串以及数值
    • @mpet 我已经编辑了我的答案以获取 img src 以及值。
    【解决方案2】:

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

    但是你可以使用这个:

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

    第一组将包含&lt;td&gt;的值

    【讨论】:

    • 你有什么建议?
    猜你喜欢
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 2021-05-24
    • 2011-05-09
    • 1970-01-01
    • 2022-08-08
    相关资源
    最近更新 更多