(PHP 5)
Supprime les caractères inutiles d'une chaîne Javascript.
<?php
function minify_js($input)
{
$output = '';
$inCommentBlock = false;
$inCommentInline = false;
$inQuotes = array();
$noSpacesAround = '{}()[]<>|!?:;,+-*/=';
$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($nextChr=='/') {
$inCommentBlock = false;
$i++;
continue 2;
}
break;
case '/':
if(!$inCommentInline && !count($inQuotes) && $nextChr=='*') {
$inCommentBlock = true;
$i++;
continue 2;
} elseif(!$inCommentBlock && !count($inQuotes) && $nextChr==='/') {
$inCommentInline = true;
$i++;
continue 2;
} else if(!$inCommentBlock && !$inCommentInline && !count($inQuotes) ) {
// C'est peut-être le début d'une RegExp
$nextN = strpos($input, "\n", $i);
$nextR = strpos($input, "\r", $i);
if($nextN===false) $nextN = $inputs_count;
if($nextR===false) $nextR = $inputs_count;
$eolPos = min($nextN, $nextR);
$eol = substr($input, $i, $eolPos-$i);
if( !preg_match('`^(\/.+\/[gim]+)(\W)`', $eol, $m) )
preg_match('`^(\/.+\/[gim]*)(\W)`', $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( !$inCommentBlock && !$inCommentInline && ( $prevChr!=='\\' || ( $prevChr==='\\' && $inputs[$i-2]==='\\') ) ) {
if(end($inQuotes)==$chr) {
array_pop($inQuotes);
} elseif(!count($inQuotes)) {
$inQuotes[] = $chr;
}
}
break;
case "\r":
case "\n":
if( $nextChr!=='/' ) {
$inCommentInline = false;
}
// break intentionally omitted
case ' ':
case "\t":
if( !count($inQuotes) ) {
if( ( strstr("{$noSpacesAround} \t\r\n", $nextChr) || strstr("{$noSpacesAround} \t\r\n", $prevChr) ) ) {
continue 2;
}
}
break;
default:
break;
}
if( !$inCommentBlock && !$inCommentInline ) {
$output .= $chr;
$prevChr = $chr;
}
}
$output = trim(preg_replace("`[\r\n]+`", "\n", $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