How can you prevent the src attribute from shifting when using preg_replace in PHP?

When using preg_replace in PHP to modify HTML content, the src attribute of an image tag may shift if not properly handled. To prevent this, you can use a regular expression pattern that specifically targets the src attribute within the image tag and replace only its value without affecting the rest of the tag.

// Example code snippet to prevent src attribute shifting when using preg_replace
$html = '<img src="image.jpg" alt="Example image">';
$new_src = 'new_image.jpg';

// Use preg_replace with a specific pattern to target only the src attribute value
$html = preg_replace('/(<img[^>]*\ssrc=["\'])[^"\']*?([^>]*>)/i', '$1' . $new_src . '$2', $html);

echo $html;