What are some common methods for adding or modifying HTML attributes in PHP?

When working with HTML in PHP, there are several common methods for adding or modifying attributes. One way is to use string concatenation to build the HTML tag with the desired attributes. Another method is to use the `setAttribute()` method if working with a DOMDocument object. Additionally, you can use PHP functions like `str_replace()` to modify existing attributes in HTML strings.

// Method 1: String concatenation to add attributes
$tag = '<a href="https://www.example.com">Link</a>';
$tagWithAttribute = str_replace('<a ', '<a target="_blank" ', $tag);
echo $tagWithAttribute;

// Method 2: Using DOMDocument to add attributes
$doc = new DOMDocument();
$doc->loadHTML('<a href="https://www.example.com">Link</a>');
$links = $doc->getElementsByTagName('a');
foreach ($links as $link) {
    $link->setAttribute('target', '_blank');
}
echo $doc->saveHTML();

// Method 3: Using str_replace() to modify existing attributes
$tag = '<img src="image.jpg" alt="Example Image">';
$modifiedTag = str_replace('alt="Example Image"', 'alt="New Alt Text"', $tag);
echo $modifiedTag;