diff --git a/src/TinyHtmlMinifier.php b/src/TinyHtmlMinifier.php index d628c06..5cbaf2e 100644 --- a/src/TinyHtmlMinifier.php +++ b/src/TinyHtmlMinifier.php @@ -71,7 +71,7 @@ public function minify(string $html) : string $html = $this->removeComments($html); } - $rest = $html; + $rest = $this->replaceJSPlaceholders($html); while (!empty($rest)) { $parts = explode('<', $rest, 2); @@ -79,7 +79,7 @@ public function minify(string $html) : string $rest = (isset($parts[1])) ? $parts[1] : ''; } - return $this->output; + return $this->restoreJSPlaceholders($this->output); } // Walk trough html @@ -283,4 +283,24 @@ private function minifyKeepSpaces($element) { return preg_replace('!\s+!', ' ', $element); } + + // Change opening and closing tags to placeholder in script tags + function replaceJSPlaceholders($string) +{ + $pattern = '/]*)>(.*?)<\/script>/s'; + $string = preg_replace_callback($pattern, function($matches) { + $attributes = $matches[1]; + $content = str_replace('<', '__OPEN_TAG__', $matches[2]); + $content = str_replace('>', '__CLOSE_TAG__', $content); + return "{$content}"; + }, $string); + + return $string; +} + + // Restore / revert opening and closing tags in script tags + private function restoreJSPlaceholders($string) + { + return str_replace(array('__OPEN_TAG__', '__CLOSE_TAG__'), array('<', '>'), $string); + } }