在PHP中,我如何使用DOMDocument类来替换IMG标签的src =属性? [英] In PHP, how can I use the DOMDocument class to replace the src= attribute of an IMG tag?

查看:209
本文介绍了在PHP中,我如何使用DOMDocument类来替换IMG标签的src =属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能够替换HTML IMG标签的src =属性而不会丢失任何其他属性通常很有用。什么是这样做的快速,非正则表达式的方式?

It's often useful to be able to swap out the src= attribute of an HTML IMG tag without losing any of the other attributes. What's a quick, non-regex way of doing this?

我不想使用RegEx的原因是:

The reasons I don't want to use RegEx are:


  1. 它不太可读。每次我需要解释一个新案例时,我都不想花20分钟解密一个模式。

  2. 我计划修改此函数以在缺失时添加宽度和高度属性。一个简单的RegEx字符串替换将不易于修改。

以下是上下文:我有一堆RSS提要每个帖子都包含一个图片。我想用空白图片替换这些图片,但保持HTML不受影响:

Here's the context: I have a bunch of RSS feed posts that each contain one image. I would like to replace these images with blank images, but keep the HTML otherwise unaffected:

$raw_post_html = "<h2>Feed Example</h2>
    <p class='feedBody'>
        <img src='http://premium.mofusecdn.com/6ff7098b3c8561d70c0af16d30e57d4e/cache/other/48da8425bc54af2d5d022f28cc8b021c.200.0.0.png' alt='Feed Post Image' width='350' height='200' />
        Feed Body Content
    </p>";

echo replace_img_src($raw_post_html, "http://cdn.company.org/blank.gif");


推荐答案

这就是我想到的。它使用PHP DOM API创建一个小型的HTML文档,然后将XML保存为IMG元素。
$ b

This is what I've come up with. It uses the PHP DOM API to create a tiny HTML document, then saves the XML for just the IMG element.

function replace_img_src($original_img_tag, $new_src_url) {
    $doc = new DOMDocument();
    $doc->loadHTML($original_img_tag);

    $tags = $doc->getElementsByTagName('img');
    if(count($tags) > 0)
    {
           $tag = $tags->item(0);
           $tag->setAttribute('src', $new_src_url);
           return $doc->saveHTML($tag);
    }

    return false;
}

注意:5.3之前版本的PHP。 6, $ doc-> saveHTML($ tag)可以更改为 $ doc-> saveXML($ tag)

Note: In versions of PHP before 5.3.6, $doc->saveHTML($tag) can be changed to $doc->saveXML($tag).

这篇关于在PHP中,我如何使用DOMDocument类来替换IMG标签的src =属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆