您不必使用正则表达式(假设您想修改从外部源加载的 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>";
工作小提琴示例。或者你可以使用更复杂一点xPath
,做得更优雅:
foreach( $xpath->query('//table/tr[td[2][not(text())]]') as $tr){
$tr->parentNode->removeChild($tr);
}