2016-10-27 4 views
-1

は、私は私の正規表現をテストする場合 - >http://www.regexr.com/3ehdaPHP:figcaptionタグであるアンカーを除くすべてのアンカータグを削除ここ

私はこのパターン<a.*>*?<\/a>で試してみましたが、それは持っているならば、それはそれをキャッチしていません新しい行は、figcaptionにあるアンカーをキャッチします。

figcaptionタグにあるアンカー以外のすべてのアンカータグを削除できますか?

正規表現とやり取りができない場合は、誰かが私にどのようにして他の方法で解決できるかのヒントを教えてください。

答えて

2

どこでも読めるので、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; 
+0

OMG、ありがとうございます。 – whitesiroi

関連する問題