2016-05-25 8 views
1

私は、いくつかの<img>要素を含むさまざまな種類のhtmlタグとstuffを含む文字列を持っています。私はタグの中にそれらの<img>要素をラップしようとしています。しかし<img>タグが隣接<figcaption>タグを持っている場合、結果はかなり醜いです、そしてフィギュア要素の浮遊終了タグを生成preg_replace stre endタグを削除するregex

preg_replace('/(<img.*?>)/s','<figure>$1</figure>',$content); 

このようにpreg_replaceを使用してこれまでのところは良いです
<figure id="attachment_9615"> 
<img class="size-full" src="http://www.example.com/pic.png" alt="name" width="1699" height="354" /> 
<figcaption class="caption-text"></figure>Caption title here</figcaption> 
</figure> 

図の中にimg-tagとfigcaption-tagの両方を囲むように、preg_replace正規表現のバリエーションをたくさん試しましたが、動作させるように見えません。

私の最新の試み:他の人が指摘したように

preg_replace('/(<img.*?>)(<figcaption .*>*.<\/figcaption>)?/s', 
'<figure">$1$2</figure>', 
$content); 
+2

[なぜ、オハイオ州なぜ正規表現と、それは決して停止しない...](HTTP:

すべてあなたのイメージの周り<figure>タグを持っているために、あなたはelseブランチを追加したい場合があります://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – trincot

+2

このタスクにRegExを使用することをお勧めしますか?あなたはDOMパーサーを考えましたか? –

+1

@RocketHazmatまあ、確か。あなたがWordPressでこれを行うための別の方法を知っているならば、FBインスタントアーティクルのRSSフィード出力をクリーンアップする目的で。おそらく、いくつかのWordpressコンテンツフィルタを削除して、それらのすべてをやり直すことはできますが、正規表現ではないでしょう...簡単ですか? –

答えて

2

は、より良いパーサーを使用する、すなわちDOMDocument代わりに。

<?php 

$html = <<<EOF 
<html> 
    <img class="size-full" src="http://www.example.com/pic.png" alt="name" width="1699" height="354" /> 
    <figcaption class="caption-text">Caption title here</figcaption> 

    <img class="size-full" src="http://www.example.com/pic.png" alt="name" width="1699" height="354" /> 

    <img class="size-full" src="http://www.example.com/pic.png" alt="name" width="1699" height="354" /> 
    <figcaption class="caption-text">Caption title here</figcaption> 
</html> 
EOF; 

$dom = new DOMdocument(); 
$dom->loadHTML($html); 
$xpath = new DOMXPath($dom); 

# get all images 
$imgs = $xpath->query("//img"); 

foreach ($imgs as $img) { 
    if ($img->nextSibling->tagName == 'figcaption') { 

     # create a new figure tag and append the cloned elements 
     $figure = $dom->createElement('figure'); 
     $figure->appendChild($img->cloneNode(true)); 
     $figure->appendChild($img->nextSibling->cloneNode(true)); 

     # insert the newly generated elements right before $img 
     $img->parentNode->insertBefore($figure, $img); 

     # and remove both the figcaption and the image from the DOM 
     $img->nextSibling->parentNode->removeChild($img->nextSibling); 
     $img->parentNode->removeChild($img); 

    } 
} 
$dom->formatOutput=true; 
echo $dom->saveHTML(); 

a demo on ideone.comを参照してください。次の兄弟が<figcaption>である場合、次のコードは、各img周り<figure>タグをラップ

} else { 
    $figure = $dom->createElement('figure'); 
    $figure->appendChild($img->cloneNode(true)); 
    $img->parentNode->insertBefore($figure, $img); 

    $img->parentNode->removeChild($img); 
} 
関連する問題