Remove whitespace from HTML

前端 未结 15 1726
花落未央
花落未央 2020-12-28 14:25

I have HTML code like:

相关标签:
15条回答
  • 2020-12-28 14:54

    $html = preg_replace('~>\s+<~', '><', $html);

    But I don't see the point of this. If you're trying to make the data size smaller, there are better options.

    0 讨论(0)
  • 2020-12-28 14:54

    As gpupo's post provided the cleanest solution for many different types of spacing formatting's. However, a minor but important piece was forgotten at the end! A final string trim :-p

    Below is a tested and working solution.

    function compress_html($content)
    {
        $i       = 0;
        $content = preg_replace('~>\s+<~', '><', $content);
        $content = preg_replace('/\s\s+/',  ' ', $content);
    
        while ($i < 5)
        {
            $content = str_replace('  ', ' ', $content);
            $i++;
        }
    
        return trim($content);
    }
    
    0 讨论(0)
  • 2020-12-28 14:57
    //...
    public function compressHtml($content)
    {
        $content = preg_replace('~>\s+<~', '><', $content);
        $content = preg_replace('/\s\s+/', ' ', $content);
        $i = 0;
        while ($i < 5) {
            $content = str_replace('  ', ' ', $content);
            $i++;    
        }
    
        return $content;
    }
    
    0 讨论(0)
提交回复
热议问题