Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions src/TinyHtmlMinifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,15 @@ public function minify(string $html) : string
$html = $this->removeComments($html);
}

$rest = $html;
$rest = $this->replaceJSPlaceholders($html);

while (!empty($rest)) {
$parts = explode('<', $rest, 2);
$this->walk($parts[0]);
$rest = (isset($parts[1])) ? $parts[1] : '';
}

return $this->output;
return $this->restoreJSPlaceholders($this->output);
}

// Walk trough html
Expand Down Expand Up @@ -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\b([^>]*)>(.*?)<\/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 "<script{$attributes}>{$content}</script>";
}, $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);
}
}