What are some best practices for handling styles generated by HTML editors in PHP applications?

When HTML editors generate styles inline or within the HTML markup, it can lead to messy and hard-to-maintain code. One way to handle this is to extract the styles into a separate CSS file and link to it from the HTML document. This separation of content and presentation helps keep the code clean and organized.

// Extract inline styles from HTML content and save them to a CSS file
function extract_styles_to_css($html_content) {
    preg_match_all('/style="([^"]+)"/', $html_content, $matches);
    $styles = implode(" ", $matches[1]);
    
    $css_file = fopen("styles.css", "w");
    fwrite($css_file, "/* Inline styles extracted from HTML */\n");
    fwrite($css_file, $styles);
    fclose($css_file);
    
    // Replace inline styles with a link to the CSS file
    $html_content = preg_replace('/<style[^>]*>.*<\/style>/s', '', $html_content);
    $html_content = preg_replace('/style="([^"]+)"/', '', $html_content);
    $html_content = str_replace('</head>', '<link rel="stylesheet" href="styles.css"></head>', $html_content);
    
    return $html_content;
}

// Example usage
$html_content = '<div style="color: red; font-size: 16px;">Hello, world!</div>';
$html_content = extract_styles_to_css($html_content);
echo $html_content;