What best practices should be followed when using regular expressions with DOM parsing in PHP to avoid issues like inflexibility and errors with CSS class additions?

Regular expressions can be powerful tools for parsing HTML content, but they can also be brittle and error-prone when used to manipulate DOM elements like CSS classes. To avoid issues like inflexibility and errors with CSS class additions, it's best to use a DOM parser like DOMDocument in PHP. This allows you to manipulate the DOM structure in a more reliable and flexible way, without relying on regular expressions.

// Create a new DOMDocument object
$doc = new DOMDocument();
$doc->loadHTML($html);

// Find all elements with a specific CSS class
$xpath = new DOMXPath($doc);
$elements = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' my-class ')]");

// Add a new CSS class to each element
foreach ($elements as $element) {
    $classAttr = $element->getAttribute('class');
    $element->setAttribute('class', trim($classAttr . ' new-class'));
}

// Output the modified HTML
echo $doc->saveHTML();