Thanks for all the feedback guys. I'll be using apache to compress the files but wanted to make something to remove all the line breaks in css and html segments of the page before hand. I couldn't find anything to do that while leaving the php and javascript untouched in a file, so I made my own script to do it.
The following code can definitely be improved and is very, very raw. There's a lot of spots where I can make it more efficient, but this is just a test of an idea. However, it's working well enough to use. Just save it to a php file, and set $file_name to the name of your file.
<?
function parsefile($file)
{
$contents = file_get_contents($file);
$contents = preg_replace('/<!--(.|\s)*?-->/', '', $contents);
$contents = str_replace('<?', ' <? ', $contents);
$contents = str_replace('?>', ' ?> ', $contents);
$contents = str_replace('<script', ' <script', $contents);
$contents = str_replace('script>', 'script> ', $contents);
$filtered = '';
$length = strlen($contents);
$ignore = Array();
$html = Array();
for($i = 0;$i <= $length;$i++)
{
if(substr($contents, $i, 2) == '<?')
{
$end = strpos($contents, '?>', $i) + 2;
array_push($ignore, Array('php', $i, $end));
$i = $end;
}
else if(strtolower(substr($contents, $i, 7)) == '<script')
{
$end = strpos($contents, '</script>', $i) + 9;
array_push($ignore, Array('js', $i, $end));
$i = $end;
}
}
$ignore_c = count($ignore) - 1;
for($i = 0;$i <= $ignore_c;$i++)
{
$start = $ignore[$i][2];
if($start < $length)
{
array_push($html, Array('html', $start+1, $ignore[$i+1][1]-1));
}
}
function cmp($a, $b)
{
if ($a[1] == $b[1]) {
return 0;
}
return ($a[1] < $b[1]) ? -1 : 1;
}
$parts = array_merge($ignore, $html);
usort($parts, "cmp");
foreach($parts as $k => $v)
{
$cont = substr($contents, $parts[$k][1], ($parts[$k][2]-$parts[$k][1]));
if($parts[$k][0] == 'html')
{
$cont = str_replace(Array("\n", "\t", " ", " ", " "), " ", $cont);
}
$filtered .= $cont;
}
return $filtered;
}
$file_name = '../main.php';
$filtered = parsefile($file_name);
echo '<textarea style="width:700px;height:600px">' . file_get_contents($file_name) . '</textarea>';
echo ' <textarea style="width:700px;height:600px">' . $filtered . '</textarea>';
?>
With some tinkering, this code can be modified to iterate through all the files in a directory and save them to another directory as minified versions.