What are the potential issues with using preg_replace to replace image tags in PHP code?

Using preg_replace to replace image tags in PHP code can be problematic because it may not account for all possible variations of image tags, leading to unexpected results or errors. To solve this issue, it's better to use a more robust HTML parsing library like DOMDocument to accurately target and replace image tags.

$html = '<img src="image.jpg"><img src="image2.jpg">';
$dom = new DOMDocument();
$dom->loadHTML($html);

$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
    $newSrc = 'new_image.jpg';
    $image->setAttribute('src', $newSrc);
}

$newHtml = $dom->saveHTML();
echo $newHtml;