diff --git a/src/CssToInlineStyles.php b/src/CssToInlineStyles.php index 8307d85..264a9d9 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; } @@ -627,11 +627,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); + } + } } /**