5

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?

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

  1. It's not very readable. I don't want to spend 20 mins deciphering a pattern every time I need to account for a new case.
  2. I am planning on modifying this function to add in width and height attributes when they're missing. A simple RegEx string replacement won't be easy to modify for this purpose.

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");
3
  • Apart from the very low quality of your question rendering it off-topic, how has that not been answered before?
    – hakre
    Jul 3, 2013 at 5:28
  • has it been answered before? Do you have a link?
    – DavidH
    Jul 3, 2013 at 15:57
  • Your question still misses the SSCC Example. Please add it. then I can better look for an exact duplicate.
    – hakre
    Jul 3, 2013 at 18:24

1 Answer 1

14

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;
}

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

2
  • +1 for dom and not regex or string methods :)
    – Dave Chen
    Jun 20, 2013 at 17:54
  • 4
    @DaveChen: actually dom uses string methods
    – Dave Chen
    Jun 20, 2013 at 17:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.