Last Updated: February 25, 2016
·
2.881K
· dhilowitz

PHP: A Quick, non-RegEx Way of Replacing an IMG tag's SRC= Attribute

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).