Remove whitespace from HTML

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

I have HTML code like:

15条回答
  •  温柔的废话
    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);
    }
    

提交回复
热议问题