当前位置:首页 > PHP教程 > php高级应用 > 列表

php实现对css文件进行压缩和解压缩

发布:smiling 来源: PHP粉丝网  添加日期:2014-06-23 08:14:46 浏览: 评论:0 

下面用php实现了一个对css进行压缩和解压缩的小程序,暂不适用于js的操作,通过这个案例可以学习php字符替换和正则替换的技术.

将css代码压缩能够减小文件的体积,从而减小了网络传输量和带宽占用,减小了服务器的处理的压力.

代码如下:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
  2.  
  3. <html xmlns="http://www.w3.org/1999/xhtml"
  4.  
  5. <head> 
  6.  
  7. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
  8.  
  9. </head> 
  10.  
  11. <?php  
  12.  
  13. $string = trim(stripslashes($_POST['code'])); //stripslashes()函数删除转义字符(反斜杠) 
  14.  
  15. if(!emptyempty($string)){ 
  16.  
  17. if($_POST['method'] == '压缩' ){ 
  18.  
  19. $string = css_compress($string); 
  20.  
  21. }elseif($_POST['method'] == '解压缩' ){ 
  22.  
  23. $string = css_decompress($string); 
  24.  
  25.  
  26. }else
  27.  
  28. $string = ''
  29.  
  30.  
  31. function css_compress($string){ 
  32.  
  33. //压缩 
  34.  
  35. $string = str_replace("\r\n","",$string); //首先去掉换行 
  36.  
  37. $string = preg_replace("/(\s*\{\s*)/","{",$string); 
  38.  
  39. $string = preg_replace("/(\s*\;\s*\}\s*)/","}",$string); //去掉反括号首位的空格和换行,和最后一个; 
  40.  
  41. $string = preg_replace("/(\s*\;\s*)/",";",$string); 
  42.  
  43. return $string
  44.  
  45.  
  46. function css_decompress($string){ 
  47.  
  48. //解压 
  49.  
  50. $string = css_compress($string); //为了效果更好,解压前,先压缩至最简状态 
  51.  
  52. $string = str_replace("{","\r\n{\r\n\t",$string); 
  53.  
  54. $string = str_replace("}","\r\n}\r\n\r\n",$string);  
  55.  
  56. $string = str_replace(";",";\r\n\t",$string); 
  57.  
  58. $string = str_replace("*/","*/\r\n",$string); 
  59.  
  60. return $string
  61.  
  62.  
  63. ?> 
  64.  
  65. <body> 
  66.  
  67.   <div style="width:800px;height:500px;text-align:center"
  68.  
  69.   <p><strong>请将css代码粘贴到下面框中,然后选择压缩/解压缩</strong></p> 
  70.  
  71.   <form action="" method="post" name="css_code"
  72.  
  73.     <textarea style="width:90%;height:460px;padding:5px;" name="code"><?php echo $string; ?></textarea> 
  74.  
  75.     <br /> 
  76.  
  77.     <input type="submit" name="method" value="压缩" /> 
  78.  
  79.     <input type="submit" name="method" value="解压缩" /> 
  80.  
  81.   </form> 
  82.  
  83.   </div> 
  84. </body> 
  85. </html> 

Tags: css文件压缩 css文件解压缩

分享到: