我有以下通过php脚本生成的HTML代码:
<table>
<tr>
<td><strong>Color</strong></td>
<td></td>
</tr>
<tr>
<td><strong>Size</strong></td>
<td>10</td>
</tr>
</table>
如果每行的第二个单元格为空,请删除该行,结果将为:
<table>
<tr>
<td><strong>Size</strong></td>
<td>10</td>
</tr>
</table>
是否可以这样做?
答案 0 :(得分:2)
您不必使用regexp(假设您要修改从外部源加载的HTML),可以使用DOM执行此操作:
<?php
$html = '<html><body><table>
<tr>
<td><strong>Color</strong></td>
<td></td>
</tr>
<tr>
<td><strong>Size</strong></td>
<td>10</td>
</tr>
</table></html>';
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
foreach( $xpath->query('//table/tr') as $tr){
$tds = $tr->getElementsByTagName('td');
// You should check whether <tr> has two <td>s or is it error
echo $tds->item(0)->nodeValue . " = " . $tds->item(1)->nodeValue . "<br/>";
if( !$tds->item(1)->nodeValue){
$tr->parentNode->removeChild($tr);
}
}
echo "<pre>" . htmlspecialchars($dom->saveHTML()) . "</pre>";
工作fiddle example。或者你可以使用更复杂的xPath
并使它更优雅:
foreach( $xpath->query('//table/tr[td[2][not(text())]]') as $tr){
$tr->parentNode->removeChild($tr);
}
答案 1 :(得分:1)
尝试使用此代码:
<table>
<?php if($color){ ?>
<tr>
<td><strong>Color</strong></td>
<td><?php echo $color ?></td>
</tr>
<?php } ?>
<?php if($size){ ?>
<tr>
<td><strong>Size</strong></td>
<td><?php echo $size ?></td>
</tr>
<?php } ?>
</table>