我有一个包含不同类型的 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 正则表达式变体来将 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();
拥有<figure>
标记所有您的图像,您可能需要添加 else
分支:
} else {
$figure = $dom->createElement('figure');
$figure->appendChild($img->cloneNode(true));
$img->parentNode->insertBefore($figure, $img);
$img->parentNode->removeChild($img);
}
关于php - preg_replace 正则表达式删除杂散结束标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37441674/