From 1200bb09cfe176b03981e54f412b003ab2db1047 Mon Sep 17 00:00:00 2001 From: "Barry vd. Heuvel" Date: Sat, 26 Jul 2014 13:16:35 +0200 Subject: [PATCH] Refactor removing style tags This uses xPath to find the style tags and either remove the style tag completely, or replace them with just the media queries, based on the excludeMediaQueries flag. This follows the logic that if the mediaqueries are excluded from inlining, they should not be stripped from the document, because they aren't processed. If for some reason they are processed (don't know the use case) they can just be removed. --- src/CssToInlineStyles.php | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/src/CssToInlineStyles.php b/src/CssToInlineStyles.php index 023b998..f6470bd 100644 --- a/src/CssToInlineStyles.php +++ b/src/CssToInlineStyles.php @@ -361,6 +361,11 @@ public function convert($outputXHTML = false) } } + // strip original style tags if we need to + if ($this->stripOriginalStyleTags) { + $this->stripOriginalStyleTags($xPath); + } + // should we output XHTML? if ($outputXHTML) { // set formating @@ -391,11 +396,6 @@ public function convert($outputXHTML = false) $html = $this->cleanupHTML($html); } - // strip original style tags if we need to - if ($this->stripOriginalStyleTags) { - $html = $this->stripOriginalStyleTags($html); - } - // return return $html; } @@ -625,11 +625,25 @@ public function setExcludeMediaQueries($on = true) * Strip style tags into the generated HTML * * @return string - * @param string $html The HTML to strip style tags. + * @param \DOMXPath $xPath The DOMXPath for the entire document. */ - private function stripOriginalStyleTags($html) + private function stripOriginalStyleTags(\DOMXPath $xPath) { - return preg_replace('|(.*)|isU', '', $html); + // Get all style tags + $nodes = $xPath->query('descendant-or-self::style'); + + foreach ($nodes as $node) { + if ($this->excludeMediaQueries) { + //Search for Media Queries + preg_match_all('/@media [^{]*{([^{}]|{[^{}]*})*}/', $node->nodeValue, $mqs); + + // Replace the nodeValue with just the Media Queries + $node->nodeValue = implode("\n", $mqs[0]); + } else { + // Remove the entire style tag + $node->parentNode->removeChild($node); + } + } } /**