What are some best practices for replacing specific attributes within HTML tags using PHP?

When working with HTML tags in PHP, there may be instances where you need to replace specific attributes within those tags. One common scenario is replacing the value of a certain attribute, such as changing the src attribute of an img tag. To achieve this, you can use PHP's built-in functions like preg_replace or DOMDocument to manipulate the HTML content and update the desired attribute.

// Sample HTML content with an img tag
$html = '<img src="old_image.jpg" alt="Old Image">';

// Replace the src attribute with a new image
$new_image = 'new_image.jpg';
$html = preg_replace('/(<img[^>]+)src="[^"]*"/', '$1src="' . $new_image . '"', $html);

echo $html;