![](/img/trans.png)
[英]PHP preg_replace remove text from substring and end tag?
[英]preg_replace regex to remove stray end tag
我有一個包含不同類型的html標簽和東西的字符串,包括一些<img>
元素。 我試圖將那些<img>
元素包裝在<figure>
標記內。 到目前為止,使用這樣的preg_replace到目前為止還不錯:
preg_replace( '/(<img.*?>)/s','<figure>$1</figure>',$content);
但是,如果<img>
標記具有相鄰的<figcaption>
標記,則結果將很難看,並為圖形元素生成一個雜散的結束標記:
<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>
我已經嘗試了很多preg_replace regex變體來將img-tag和figcaption-tag都包裝在圖中,但是似乎無法使其正常工作。
我的最新嘗試:
preg_replace( '/(<img.*?>)(<figcaption .*>*.<\/figcaption>)?/s',
'<figure">$1$2</figure>',
$content);
正如其他人指出的那樣,最好使用解析器,即DOMDocument
。 以下代碼將<figure>
標記包裝在每個img
周圍,其中下一個兄弟姐妹是<figcaption>
:
<?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();
在ideone.com上查看演示 。
要在所有圖像周圍使用<figure>
標簽,您可能需要添加else
分支:
} else {
$figure = $dom->createElement('figure');
$figure->appendChild($img->cloneNode(true));
$img->parentNode->insertBefore($figure, $img);
$img->parentNode->removeChild($img);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.