代码之家  ›  专栏  ›  技术社区  ›  Davinder Kumar

特殊字符显示无效

  •  1
  • Davinder Kumar  · 技术社区  · 7 年前

    我正在使用一种动态压缩HTML的方法。下面是函数

    function compress_page($buffer) {
        $search = array(
            '/\>[^\S ]+/s', /*strip whitespaces after tags, except space*/
            '/[^\S ]+\</s', /*strip whitespaces before tags, except space*/
            '/(\s)+/s',  /*shorten multiple whitespace sequences*/
        );
        $replace = array(
            '>',
            '<',
            '\\1',
        );
        $buffer = preg_replace($search, $replace, $buffer);
        return $buffer;
    }
    

    我尝试了其他缩小HTML的方法,但也遇到了同样的问题。

    2 回复  |  直到 7 年前
        1
  •  0
  •   Moshe Harush    7 年前

    这可能是因为您没有向正则表达式添加Unicode标志支持。

    无论如何,我写了一个代码来缩小:

    function sanitize_output($buffer, $type = null) {
    
            $search = array(
                '/\>[^\S ]+/s',     // strip whitespaces after tags, except space
                '/[^\S ]+\</s',     // strip whitespaces before tags, except space
                '/(\s)+/s',         // shorten multiple whitespace sequences
                '/<!--(.|\s)*?-->/', // Remove HTML comments
                '#/\*(.|\s)*\*/#Uu' // Remove JS comments
            );
    
            $replace = array(
                '>',
                '<',
                ' ',
                '',
                ''
            );
    
    
            if( $type == 'html' ){
                // Remove quets of attributs
                $search[] = '#(\w+=)(?:"|\')((\S|\.|\-|/|_|\(|\)|\w){1,8})(?:"|\')#u';
                $replace[] = '$1$2';
    
                // Remove spaces beetween tags
                $search[] = '#(>)\s+(<)#mu';
                $replace[] = '$1$2';
            }
    
            $buffer = str_replace( PHP_EOL, '', preg_replace( $search, $replace, $buffer ) );
    
            return $buffer;
        }
    
        2
  •  0
  •   Davinder Kumar    6 年前

    function pt_html_minyfy_finish( $html )  {
      $html = preg_replace('/<!--(?!s*(?:[if [^]]+]|!|>))(?:(?!-->).)*-->/s', '', $html);
      $html = str_replace(array("\r\n", "\r", "\n", "\t"), '', $html);
      while ( stristr($html, '  '))
         $html = str_replace('  ', ' ', $html);
     return $html;
    }
    

    希望这能帮助别人!