PHP - Remove newlines and spaces from StyleSheet
- Joel Lipman
- Personal Home Page
- Hits: 3019
What?
This is a quick note on how to reduce a whole bunch of CSS into a single line without unnecessary spaces and new lines.
Why?
What I have:
#copyright a{ margin: 10px 0 0 85px; box-shadow: 5px 5px 5px 0px rgba(51, 51, 51, 0.3); }
- #copyright a{
- margin: 10px 0 0 85px;
- box-shadow: 5px 5px 5px 0px rgba(51, 51, 51, 0.3);
- }
What I want:
#copyright a{margin:10px 0 0 85px;box-shadow:5px 5px 5px 0px rgba(51,51,51,0.3);}
- #copyright a{margin:10px 0 0 85px;box-shadow:5px 5px 5px 0px rgba(51,51,51,0.3);}
How?
So I'm doing this with a regular expression to get rid of newlines:
$v_AppStyle = " #copyright a{ margin: 10px 0 0 85px; box-shadow: 5px 5px 5px 0px rgba(51, 51, 51, 0.3); }"; $v_AppStyleFormatted = preg_replace('/\s+/', ' ', $v_AppStyle);
- $v_AppStyle = "
- #copyright a{
- margin: 10px 0 0 85px;
- box-shadow: 5px 5px 5px 0px rgba(51, 51, 51, 0.3);
- }";
- $v_AppStyleFormatted = preg_replace('/\s+/', ' ', $v_AppStyle);
and a few str_replace arrays:
// exceptions $a_ReplaceFrom1 = array("px ", "0 ", " a"); $a_ReplaceTo1 = array("px?", "0?", "?a"); $v_AppStyleFormatted = str_replace($a_ReplaceFrom1, $a_ReplaceTo1, $v_AppStyleFormatted); // replace all spaces to empty and replace question marks back to spaces $a_ReplaceFrom2 = array(" ", "?"); $a_ReplaceTo2 = array("", " "); $v_AppStyleFormatted = str_replace($a_ReplaceFrom2, $a_ReplaceTo2, $v_AppStyleFormatted); echo $v_AppStyleFormatted;
- // exceptions
- $a_ReplaceFrom1 = array("px ", "0 ", " a");
- $a_ReplaceTo1 = array("px?", "0?", "?a");
- $v_AppStyleFormatted = str_replace($a_ReplaceFrom1, $a_ReplaceTo1, $v_AppStyleFormatted);
- // replace all spaces to empty and replace question marks back to spaces
- $a_ReplaceFrom2 = array(" ", "?");
- $a_ReplaceTo2 = array("", " ");
- $v_AppStyleFormatted = str_replace($a_ReplaceFrom2, $a_ReplaceTo2, $v_AppStyleFormatted);
- echo $v_AppStyleFormatted;