diff --git a/src/Css/Processor.php b/src/Css/Processor.php index 0c5ceb1..94ee607 100644 --- a/src/Css/Processor.php +++ b/src/Css/Processor.php @@ -2,6 +2,8 @@ namespace TijsVerkoyen\CssToInlineStyles\Css; +use DOMDocument; +use DOMElement; use TijsVerkoyen\CssToInlineStyles\Css\Rule\Processor as RuleProcessor; use TijsVerkoyen\CssToInlineStyles\Css\Rule\Rule; @@ -33,20 +35,39 @@ public function getRules($css, $existingRules = array()) */ public function getCssFromStyleTags($html) { + $document = new DOMDocument('1.0', 'UTF-8'); + $internalErrors = libxml_use_internal_errors(true); + $document->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); + libxml_use_internal_errors($internalErrors); + $css = ''; - $matches = array(); - $htmlNoComments = preg_replace('||s', '', $html); - preg_match_all('||isU', $htmlNoComments, $matches); - if (!empty($matches[1])) { - foreach ($matches[1] as $match) { - $css .= trim($match) . "\n"; - } + /** @var DOMElement $style */ + foreach ($document->getElementsByTagName('style') as $style) { + $css .= $this->trimHtmlComments($style->nodeValue) . "\n"; } return $css; } + /** + * @param string $css + * @return string + */ + protected function trimHtmlComments($css) + { + $css = trim($css); + if (strncmp('') { + $css = substr($css, 0, -3); + } + + return trim($css); + } + /** * @param string $css * diff --git a/tests/Css/ProcessorTest.php b/tests/Css/ProcessorTest.php index e3d6e46..0914e60 100644 --- a/tests/Css/ProcessorTest.php +++ b/tests/Css/ProcessorTest.php @@ -261,6 +261,23 @@ public function testStyleTagsInCommentInHtml()
foo