PHP TIP: A quick, non-RegEx way of replacing an IMG tag’s SRC= attribute

Posted on June 25, 2013 by David Hilowitz

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. Here’s a quick, non-regex way of doing this. 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->saveXML($tag);
    }

    return false;
}


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

4 Comments »

  1. […] post PHP TIP: A quick, non-RegEx way of replacing an IMG tag’s SRC= attribute appeared first on Adorno […]

    Pingback by PHP TIP: A quick, non-RegEx way of replacing an IMG tag’s SRC= attribute | Dave Hilowitz — June 28, 2013 @ 9:10 pm

  2. Wow, that’s what I was exploring for, what a information! present
    here at this blog, thanks admin of this web
    site.

    Comment by Pensions — July 24, 2014 @ 8:48 pm

  3. It’s awesome designed for me to have a site, which is
    helpful in favor of my know-how. thanks admin

    Comment by dorset wedding — July 31, 2014 @ 11:20 pm

  4. I’ll immediately clutch your rss as I can’t to find your email subscription hyperlink or newsletter service.
    Do you’ve any? Please permit me recognise so that I may subscribe.
    Thanks.

    Comment by Online Hotel Bookings — August 24, 2014 @ 12:02 am

Leave a comment