Remove whitespace from HTML

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

I have HTML code like:

15条回答
  •  时光取名叫无心
    2020-12-28 14:45

    It's been a while since this question was first asked but I still see the need to post this answer in order to help people with the same problem.

    None of these solutions were adoptabe for me therefore I've came up with this solution: Using output_buffer.

    The function ob_start accepts a callback as an argument which is applied to the whole string before outputting it. Therefore if you remove whitespace from the string before flushing the output, there you're done.

    /** 
     * Remove multiple spaces from the buffer.
     * 
     * @var string $buffer
     * @return string
     */
    function removeWhitespace($buffer)
    {
        return preg_replace('/\s+/', ' ', $buffer);
    }
    
    ob_start('removeWhitespace');
    
    
    
        
        
    
    
    ob_get_flush();
    

    The above would print something like:

          
    

    Hope that helps.

    HOW TO USE IT IN OOP

    If you're using object-orientated code in PHP you may want to use a call-back function that is inside an object.

    If you have a class called, for instance HTML, you have to use this code line

    ob_start(["HTML","removeWhitespace"]); 
    

提交回复
热议问题