Use HTMLPurifier_Filter_ExtractStyleBlocks to extract and clean <style> blocks
masterThe HTMLPurifier_Filter_ExtractStyleBlocks filter identifies <style> blocks within input HTML, removes them from the main HTML stream to prevent inline styling, and cleans the CSS content using csstidy.
The extracted and cleaned CSS blocks are stored in the HTMLPurifier_Context under the key 'StyleBlocks'. This allows you to retrieve the cleaned styles later to place them in a single <style> tag in the document head or elsewhere.
Key behaviors:
- Extraction: It uses regex to find
<style>tags and moves their content to the context. - Cleaning: It uses
csstidyto format and validate the CSS. - Validation: It validates CSS selectors against allowed HTML elements and validates CSS properties against the
CSSdefinition in theHTMLPurifier_Config. - Escaping: If configured, it escapes special characters (
<,>,&) within the CSS to prevent injection attacks (e.g., viafont-family).
// Assuming $purifier is an instance of HTMLPurifier
// and the ExtractStyleBlocks filter has been added to the configuration.
$html = '<p>Hello</p><style>body { color: red; }</style>';
$clean_html = $purifier->purify($html);
// Retrieve the cleaned CSS blocks from the context
$context = $purifier->context;
$style_blocks = $context->get('StyleBlocks');
// $style_blocks now contains ['body { color: red; }']