How to change tag attributes in the output?

Good day to all. There is a blog. From the database displays the content. In content there are images and some user-made lazy-load
<img class="main-image lazy-load img-responsive" src="/img/loading.svg" alt="TOP 10: Ranking the best exhaust fans" data-src="/uploads/blog/main/thumb/top_950_500.jpg">

The task is to change the values of the attributes "data-src" and "src" in some places to output to the page. This is for the bot to scan it processed images with normal URLs.
The difficulty lies in the fact that pictures in the text a lot and not everyone has "data-src".
Help please, is the second day of head scratching.

UPD: tried to replace with the help of this function
replaceImageDataSrc function($content)
{
 $dom = new DOMDocument();
$dom->loadHTML($content);
 $images = $dom->getElementsByTagName('img');

 foreach ($images as $image) {
 $dataSrc = $image->getAttribute('data-src');
 $src = $image->getAttribute('src');
 $image->setAttribute('src', $dataSrc);
 $image->setAttribute('data-src', $src);
}

 return $dom->saveHTML();
 }

but not so in the content somewhere there are unclosed tags and DOMDocument falls into error.
Need another way
April 19th 20 at 12:29
0 answer

Find more questions by tags PHP