博文 > php压缩html代码

php压缩html代码

Php 10002019-06-28 17:55:18

php压缩html代码

优点:网络请求文件大小

  1. /**
  2. * Name: 压缩html代码
  3. * Author: Tinymeng <666@majiameng.com>
  4. * @param string $html_source
  5. * @return string
  6. */
  7. static public function compressHtml($html_source){
  8. // return trim(preg_replace(["/> *([^ ]*) *</","//","'/\*[^*]*\*/'","/\r\n/","/\n/","/\t/",'/>[ ]+</',"/ 0=['\"](.*?)['\"]/"], [">\\1<",'','','','','','><',''],$html_source));
  9. $chunks = preg_split('/(<!--<nocompress>-->.*?<!--<\/nocompress>-->|<nocompress>.*?<\/nocompress>|<pre.*?\/pre>|<textarea.*?\/textarea>|<script.*?\/script>)/msi', $html_source, -1, PREG_SPLIT_DELIM_CAPTURE);
  10. $compress = '';
  11. foreach ($chunks as $c) {
  12. if (strtolower(substr($c, 0, 19)) == '<!--<nocompress>-->') {
  13. $c = substr($c, 19, strlen($c) - 19 - 20);
  14. $compress .= $c;
  15. continue;
  16. } elseif (strtolower(substr($c, 0, 12)) == '<nocompress>') {
  17. $c = substr($c, 12, strlen($c) - 12 - 13);
  18. $compress .= $c;
  19. continue;
  20. } elseif (strtolower(substr($c, 0, 4)) == '<pre' || strtolower(substr($c, 0, 9)) == '<textarea') {
  21. $compress .= $c;
  22. continue;
  23. } elseif (strtolower(substr($c, 0, 7)) == '<script' && strpos($c, '//') != false && (strpos($c, "\r") !== false || strpos($c, "\n") !== false)) { // JS代码,包含“//”注释的,单行代码不处理
  24. $tmps = preg_split('/(\r|\n)/ms', $c, -1, PREG_SPLIT_NO_EMPTY);
  25. $c = '';
  26. foreach ($tmps as $tmp) {
  27. if (strpos($tmp, '//') !== false) { // 对含有“//”的行做处理
  28. if (substr(trim($tmp), 0, 2) == '//') { // 开头是“//”的就是注释
  29. continue;
  30. }
  31. $chars = preg_split('//', $tmp, -1, PREG_SPLIT_NO_EMPTY);
  32. $is_quot = $is_apos = false;
  33. foreach ($chars as $key => $char) {
  34. if ($char == '"' && !$is_apos && $key > 0 && $chars[$key - 1] != '\\') {
  35. $is_quot = !$is_quot;
  36. } elseif ($char == '\'' && !$is_quot && $key > 0 && $chars[$key - 1] != '\\') {
  37. $is_apos = !$is_apos;
  38. } elseif ($char == '/' && $chars[$key + 1] == '/' && !$is_quot && !$is_apos) {
  39. $tmp = substr($tmp, 0, $key); // 不是字符串内的就是注释
  40. break;
  41. }
  42. }
  43. }
  44. $c .= $tmp;
  45. }
  46. }
  47. $c = preg_replace('/[\\n\\r\\t]+/', ' ', $c); // 清除换行符,清除制表符
  48. $c = preg_replace('/\\s{2,}/', ' ', $c); // 清除额外的空格
  49. $c = preg_replace('/>\\s</', '> <', $c); // 清除标签间的空格
  50. $c = preg_replace('/\\/\\*.*?\\*\\//i', '', $c); // 清除 CSS & JS 的注释
  51. $c = preg_replace('/<!--[^!]*-->/', '', $c); // 清除 HTML 的注释
  52. $compress .= $c;
  53. }
  54. return $compress;
  55. }