Skip to content

Instantly share code, notes, and snippets.

@justindmartin
Last active September 2, 2017 14:20
Show Gist options
  • Save justindmartin/5079745 to your computer and use it in GitHub Desktop.
Save justindmartin/5079745 to your computer and use it in GitHub Desktop.
CSS, JS, and HTML minifier, written in PHP - requires JSMin.php
<?php
/* require JSMin class file */
require_once('JSMin.class.php');
class minifier{
function __Construct(){
}
function minifyCSS($CSS) {
/* remove comments */
$CSS = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $CSS);
/* remove tabs, spaces, newlines, etc. */
$CSS = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $CSS);
return $CSS;
}
function minifyFile($fileName){
$input = file_get_contents($fileName);
if(substr($fileName,-3) == 'css' && stripos($fileName,'.min.css') === false){
$newFileName = substr($fileName,0,strlen($fileName)-3) . 'min.css';
$output = $this->minifyCSS($input);
file_put_contents($newFileName,$output);
}
else if(substr($fileName,-2) == 'js' && stripos($fileName,'.min.js') === false){
$newFileName = substr($fileName,0,strlen($fileName)-2) . 'min.js';
$output = JSMin::minify($input);
file_put_contents($newFileName,$output);
}
else if(substr($fileName,-3) == 'php' && stripos($fileName, '.min.php') === false){
$newFileName = substr($fileName,0,strlen($fileName)-3) . 'min.php';
$output = $this->minifyHTML($input);
file_put_contents($newFileName,$output);
}
}
function minifyHTML($HTML) {
$HTML = str_replace("\n?>",' ?>',$HTML);
/* remove tabs, spaces, newlines, etc. */
$HTML = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $HTML);
/* add space between <?php and first character of code */
$HTML = preg_replace('/(<?php)/', '$0 ', $HTML);
/* replace 2 spaces after <?php with one */
return str_replace(' ',' ',$HTML);
}
}
?>
@Sangeeta-Singh
Copy link

may u please guide tht how to use it..?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment