どこでも読めるので、regexesはhtml(あまりにも多くのトラップを含む)を解析する信頼できる方法ではありません。 PHPには、html文字列を解析、照会、編集するクラスがあります。
$dom = new DOMDocument;
# prevent errors for badly formatted html to be displayed and store them
libxml_use_internal_errors(true);
# parse the html content wrapped in a root tag with an xml declaration to specify
# the encoding, and build the DOM tree
$dom->loadHTML('<?xml encoding="UTF-8"?><div>' . $html . '<\div>', LIBXML_HTML_NOIMPLIED);
# clear the html errors
libxml_clear_errors();
$xp = new DOMXPath($dom);
$nodeList = $xp->query('//a[not(./ancestor::figcaption)]');
# remove the selected nodes
foreach($nodeList as $node) {
$node->parentNode->removeChild($node);
}
# build the result string concatenating root child nodes
$result = '';
foreach($dom->documentElement->childNodes as $childNode) {
$result .= $dom->saveHTML($childNode);
}
echo $result;
OMG、ありがとうございます。 – whitesiroi