Hier ein neuer Versuch, die Codeschnippsel-Funktion hier im Forum ist ein graus. Also, die Funktion ist ein 1 zu 1 Ersatz für eure aktuelle Funktion. Sie ist lediglich schnell, wodurch es zu keinem Performance-Problem kommt. Ansonsten produziert sie identischen Code zu eurer aktuellen Funktion.
public function minify(string $content): string
{
$blocks = [];
$regex = '!]*?>.*?\1>!is';
// It is assumed that this placeholder could not appear organically in your
// output. If it can, you may have an XSS problem.
$placeholder = "@@@@";
$placeholderLength = strlen($placeholder);
// Replace all the tags (including their content) with a placeholder, and keep their contents for later.
$content = preg_replace_callback(
$regex,
function ($match) use (&$blocks, $placeholder) {
$blocks[] = $match[0];
return $placeholder;
},
$content
);
// Remove whitespace (spaces, newlines and tabs)
$content = trim(preg_replace('/[\n\t]{2,}|[\n\t]/m', ' ', $content));
// Iterate the blocks we replaced with placeholders beforehand, and replace the placeholders
// with the original content.
$position = 0;
foreach ($blocks as $block) {
$position = strpos($content, $placeholder, $position);
if ($position === false) {
throw new \RuntimeException("Found too many placeholders in input string");
}
$content = substr_replace($content, $block, $position, $placeholderLength);
}
return $content;
}