下面用php實現了一個對css進行壓縮和解壓縮的小程序,暫不適用于js的操作,通過這個案例可以學習php字符替換和正則替換的技術.
將css代碼壓縮能夠減小文件的體積,從而減小了網絡傳輸量和帶寬占用,減小了服務器的處理的壓力.
代碼如下:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- </head>
- <?php
- $string = trim(stripslashes($_POST['code'])); //stripslashes()函數刪除轉義字符(反斜杠)
- if(!emptyempty($string)){
- if($_POST['method'] == '壓縮' ){
- $string = css_compress($string);
- }elseif($_POST['method'] == '解壓縮' ){
- $string = css_decompress($string);
- }
- }else{
- $string = '';
- }
- function css_compress($string){
- //壓縮
- $string = str_replace("/r/n","",$string); //首先去掉換行
- $string = preg_replace("/(/s*/{/s*)/","{",$string);
- $string = preg_replace("/(/s*/;/s*/}/s*)/","}",$string); //去掉反括號首位的空格和換行,和最后一個;
- $string = preg_replace("/(/s*/;/s*)/",";",$string);
- return $string;
- }
- function css_decompress($string){
- //解壓
- $string = css_compress($string); //為了效果更好,解壓前,先壓縮至最簡狀態
- $string = str_replace("{","/r/n{/r/n/t",$string);
- $string = str_replace("}","/r/n}/r/n/r/n",$string);
- $string = str_replace(";",";/r/n/t",$string);
- $string = str_replace("*/","*//r/n",$string);
- return $string;
- }
- ?>
- <body>
- <div style="width:800px;height:500px;text-align:center">
- <p><strong>請將css代碼粘貼到下面框中,然后選擇壓縮/解壓縮</strong></p>
- <form action="" method="post" name="css_code">
- <textarea style="width:90%;height:460px;padding:5px;" name="code"><?php echo $string; ?></textarea>
- <br />
- <input type="submit" name="method" value="壓縮" />
- <input type="submit" name="method" value="解壓縮" />
- </form>
- </div>
- </body>
- </html>
新聞熱點
疑難解答