Last active
September 21, 2017 19:53
-
-
Save GuilhermeRossato/ac77ca500cb991fa4d2026a43480e292 to your computer and use it in GitHub Desktop.
Minify inner CSS string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Applicable to strings which would go inside a style property of an element, like so: | |
* element.setAttribute("style",minifyStyle(`margin : 0px 5px 4px 10px;`)); // This would remove 4 unnecessary spaces from the string | |
*/ | |
const minifyStyle = (s, mode=0) => s.replace(/(\r\n|\t|\n|\r)/gm,"").split('').filter((char, index) => (((((mode == 1)&&(mode = 2))||true)&&(((char == ':')&&(mode = 1))||true)&&(char == ';')&&(mode = 0)||true)&&mode == 0)?(char !== ' '):((mode == 2)?((mode = 3)&&(char != ' ')):true)).join(''); | |
minifyStyle(`margin-top: 5px; | |
margin: 5px 5px 5px 6px; | |
background-image: url(...) center center no-repeat; | |
`); | |
// Returns: "margin-top:5px;margin:5px 5px 5px 6px;background-image:url(...) center center no-repeat;" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Applicable to strings which would go inside a style property of an element, like so: | |
* element.setAttribute("style",minifyStyle(`margin : 0px 5px 4px 10px;`)); // This would remove 4 unnecessary spaces from the string | |
*/ | |
function minifyStyle($content) { | |
$mode = 0; | |
$clean = preg_replace("/(\r\n|\t|\n|\r)/m","", $content); | |
$exploded = str_split($clean); | |
$filtered = ""; | |
foreach($exploded as $char) { | |
if ($mode == 0 || $mode == 2 || $mode === 1) { | |
if ($mode === 1) { | |
$mode = 5; | |
} elseif ($char == ":") { | |
$mode = 1; | |
} elseif ($char === "/" && $mode === 0) { | |
$mode = 2; | |
} elseif ($char === "*" && $mode === 2) { | |
$mode = 3; | |
} elseif ($mode === 2) { | |
$mode = 0; | |
} | |
if ($char !== ' ') { | |
$filtered .= $char; | |
} | |
} elseif ($mode === 5) { | |
if ($char == ";") { | |
$mode = 0; | |
} | |
$filtered .= $char; | |
} elseif ($mode === 3 || $mode == 4) { | |
if ($char === "*" && $mode === 3) { | |
$mode = 4; | |
} else if ($char === "/" && $mode === 4) { | |
$mode = 0; | |
$filtered .= "/\n"; | |
continue; | |
} else if ($mode === 4) { | |
$mode = 3; | |
} | |
$filtered .= $char; | |
} | |
}; | |
return $filtered; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment