Search code examples
phpregexpreg-replacepreg-replace-callback

Preg replace image src using callback


I have an article with HTML tags. It's a long article with 3/5 images. Now I want to update every image src attributes. Example:

Image html tag looks like:

<img class="aligncenter" style="display: block;margin-left:auto;margin-right:auto;" src="http://img.zszywka.com/0/0269/w_0980/moj-swiat/muza-2013-najnowsze-eska-hity-2013-.jpg" width="642" />

I want to take this URL, make some changes and next update src. Then go to next image and do it again (so script must change all images src)

Final img tag looks like:

<img class="aligncenter" style="display: block;margin-left:auto;margin-right:auto;" src="http://EXMAPLE.COM/0/0269/w_0980/moj-swiat/muza-2013-najnowsze-eska-hity-2013-.jpg" width="642" />

So I need to manipulate with changes. I try using preg_replace_callback but I have a problem with it:

// change image src


$finalContent = preg_replace_callback('/' . preg_quote('src="(*.?)"') . '/', 
function() use ($variable_with_changes){ return $variable_with_changes; }, $variable_with_article_content);

echo $finalContent;

This doesn't works, I don't have an idea how I can update image domain and keep path.


Solution

  • You should be parsing HTML as HTML, not using regular expressions.

    $doc = new DOMDocument();
    $doc->loadHTML('<html><body><img class="aligncenter" style="display: block;margin-left:auto;margin-right:auto;" src="http://img.zszywka.com/0/0269/w_0980/moj-swiat/muza-2013-najnowsze-eska-hity-2013-.jpg" width="642" /></body></html>');
    $images = $doc->getElementsByTagName('img');
    foreach ($images as $img) {
        $url = $img->getAttribute('src');
        // do whatever you need to with $url
        $url = str_replace('img.zszywka.com', 'example.com', $url);
        $img->setAttribute('src', $url);
    }
    echo $doc->saveHTML();