我有一个html文件,其中包含以下表行:
<tr>
<td class="color21 right" style="font-size:12px; line-height:1.2;"> 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值?
使用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');
}
}
如果您真的想用正则表达式解析html ,请仔细考虑
但你可以使用这个:
<td.+?>(.+?)</td>
第一组将包含<td>
的值