php - preg_replace 正则表达式删除杂散结束标记

标签 php regex preg-replace

我有一个包含不同类型的 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();

参见a demo on ideone.com

拥有<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/

相关文章:

regex - 如何在 Scala 中识别表情符号?

javascript - 图像 URL javascript 正则表达式以适应特殊 url

php - 如果是 URL 的一部分,如何忽略正则表达式?

php - 使用 Delphi TidHttp 抓取时检测客户端重定向

php - 具有多种功能的产品的数据库设计

php - 将带有缩略图的图像上传到文件夹并添加到 Mysql 的路径

python - 使用 python 的 RegEx {m,n} 操作,但对 m 和 n 使用变量

php - 将 BBCode [IMG] 转换为 <img>

php - 在 SQLite3 中避免 SQL 注入(inject)

PHP Codeigniter 数据库助手类 "No tables used"