dourui7186 2017-05-14 12:48
浏览 32
已采纳

在P标签内preg_replace目标图像

I am using preg_replace to change some content, I have 2 different types of images...

<p>
    <img class="responsive" src="image.jpg">
</p>

<div class="caption">
    <img class="responsive" src="image2.jpg">
</div>

I am using preg_replace like this to add a container div around images...

function filter_content($content)
    {
        $pattern = '/(<img[^>]*class=\"([^>]*?)\"[^>]*>)/i';
        $replacement = '<div class="inner $2">$1</div>';
        $content = preg_replace($pattern, $replacement, $content);
        return $content;
    }

Is there a way to modify this so that it only affect images in P tags? And also vice versa so I can also target images within a caption div?

  • 写回答

2条回答 默认 最新

  • dongyan3853 2017-05-14 13:02
    关注

    Absolutely.

    $dom = new DOMDocument();
    $dom->loadHTML("<body><!-- DOMSTART -->".$content."<!-- DOMEND --></body>");
    $xpath = new DOMXPath($dom);
    $images = $xpath->query("//p/img");
    foreach($images as $img) {
        $wrap = $dom->createElement("div");
        $wrap->setAttribute("class","inner ".$img->getAttribute("class"));
        $img->parentNode->replaceChild($wrap,$img);
        $wrap->appendChild($img);
    }
    $out = $dom->saveHTML();
    preg_match("/<!-- DOMSTART -->(.*)<!-- DOMEND -->/s",$out,$match);
    return $match[1];
    

    It's worth noting that while parsing arbitrary HTML with regex is a disaster waiting to happen, using a parser with markers and then matching based on those markers is perfectly safe.

    Adjust the XPath query and/or inner manipulation as needed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳