2011-07-23 89 views
1

可能重複:
How to minify php page html output?如何在PHP中壓縮html輸出?

我的意思是去掉所有的換行和空格在HTML並把它放在一行。

我嘗試這個功能

public static function htmlCompress($html) 
{ 
    preg_match_all('!(<(?:code|pre|script).*>[^<]+</(?:code|pre|script)>)!',$html,$pre); 
    $html = preg_replace('!<(?:code|pre).*>[^<]+</(?:code|pre)>!', '#pre#', $html); 
    $html = preg_replace('#<!–[^\[].+–>#', '', $html); 
    $html = preg_replace('/[\r\n\t]+/', ' ', $html); 
    $html = preg_replace('/>[\s]+</', '><', $html); 
    $html = preg_replace('/[\s]+/', ' ', $html); 
    if (!empty($pre[0])) { 
     foreach ($pre[0] as $tag) { 
      $html = preg_replace('!#pre#!', $tag, $html,1); 
     } 
    } 
    return $html; 
} 

,但有時會出現像符號「」因爲這個串

$html = preg_replace('/[\s]+/', ' ', $html); 

爲什麼會出現這個符號,以及如何壓縮HTML的?

+4

使用現有的庫[HTML minifier(http://code.google.com/p/htmlcompressor/) – Ibu

+0

這通常意味着在你的字符集不匹配,例如,一個是ASCII和其他UTF -8。 –

+2

只需對內容進行壓縮即可獲得更多成果。 HTML minifaction僅適用於擁有大量用戶羣的網站。 – Gordon

回答

4

\ S不應該出現在方括號,即這是正確的:

$html = preg_replace('/\s+/', ' ', $html); 
+0

精彩而簡單,謝謝。它是唯一一個不破壞代碼。一個建議添加:$ html = str_replace('><', '><',$ html); – Codebeat