Print

PHP - Remove newlines and spaces from StyleSheet

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:

copyraw
#copyright a{
    margin: 10px 0 0 85px;
    box-shadow: 5px 5px 5px 0px rgba(51, 51, 51, 0.3);
}
  1.  #copyright a{ 
  2.      margin: 10px 0 0 85px
  3.      box-shadow: 5px 5px 5px 0px rgba(51, 51, 51, 0.3)
  4.  } 

What I want:

copyraw
#copyright a{margin:10px 0 0 85px;box-shadow:5px 5px 5px 0px rgba(51,51,51,0.3);}
  1.  #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:

copyraw
$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);
  1.  $v_AppStyle = " 
  2.  #copyright a{ 
  3.      margin: 10px 0 0 85px
  4.      box-shadow: 5px 5px 5px 0px rgba(51, 51, 51, 0.3)
  5.  }"
  6.  $v_AppStyleFormatted = preg_replace('/\s+/', ' ', $v_AppStyle)

and a few str_replace arrays:

copyraw
// 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;
  1.  // exceptions 
  2.  $a_ReplaceFrom1 = array("px ", "0 ", " a")
  3.  $a_ReplaceTo1 = array("px?", "0?", "?a")
  4.  $v_AppStyleFormatted = str_replace($a_ReplaceFrom1, $a_ReplaceTo1, $v_AppStyleFormatted)
  5.   
  6.  // replace all spaces to empty and replace question marks back to spaces 
  7.  $a_ReplaceFrom2 = array(" ", "?")
  8.  $a_ReplaceTo2 = array("", " ")
  9.  $v_AppStyleFormatted = str_replace($a_ReplaceFrom2, $a_ReplaceTo2, $v_AppStyleFormatted)
  10.  echo $v_AppStyleFormatted
Category: Personal Home Page :: Article: 697