(PHP 5)
Supprime les caractères inutiles d'une chaîne Javascript.
function minify_js($input)
{
$output = '';
$inQuotes = array();
$noSpacesAround = '{}()[]<>|&!?:;,+-*/="\'';
$input = preg_replace("`(\r\n|\r)`", "\n", $input);
$inputs = str_split($input);
$inputs_count = count($inputs);
$prevChr = null;
for ($i = 0; $i < $inputs_count; $i++) {
$chr = $inputs[$i];
$nextChr = $i+1 < $inputs_count ? $inputs[$i+1] : null;
switch($chr) {
case '/':
if (!count($inQuotes) && $nextChr == '*' && $inputs[$i+2] != '@') {
$i = 1 + strpos($input, '*/', $i);
continue 2;
} elseif (!count($inQuotes) && $nextChr == '/') {
$i = strpos($input, "\n", $i);
continue 2;
} elseif (!count($inQuotes)) {
// C'est peut-être le début d'une RegExp
$eolPos = strpos($input, "\n", $i);
if($eolPos===false) $eolPos = $inputs_count;
$eol = substr($input, $i, $eolPos-$i);
if (!preg_match('`^(/.+(?<=\\\/)/(?!/)[gim]*)[^gim]`U', $eol, $m)) {
preg_match('`^(/.+(?<!/)/(?!/)[gim]*)[^gim]`U', $eol, $m);
}
if (isset($m[1])) {
// C'est bien une RegExp, on la retourne telle quelle
$output .= $m[1];
$i += strlen($m[1])-1;
continue 2;
}
}
break;
case "'":
case '"':
if ($prevChr != '\\' || ($prevChr == '\\' && $inputs[$i-2] == '\\')) {
if (end($inQuotes) == $chr) {
array_pop($inQuotes);
} elseif (!count($inQuotes)) {
$inQuotes[] = $chr;
}
}
break;
case ' ':
case "\t":
case "\n":
if (!count($inQuotes)) {
if ( strstr("{$noSpacesAround} \t\n", $nextChr)
|| strstr("{$noSpacesAround} \t\n", $prevChr)
) {
continue 2;
}
$chr = ' ';
}
break;
default:
break;
}
$output .= $chr;
$prevChr = $chr;
}
$output = trim($output);
$output = str_replace(';}', '}', $output);
return $output;
}
?>
string minify_js ( string $input )
Retourne la chaîne input dépourvue de caractère inutile.
Commentaire(s)
Poster un commentaire