Replace multiple newlines, tabs, and spaces

前端 未结 10 1883
情深已故
情深已故 2020-11-27 05:56

I want to replace multiple newline characters with one newline character, and multiple spaces with a single space.

I tried preg_replace(\"/\\n\\n+/\", \"\\n\",

10条回答
  •  隐瞒了意图╮
    2020-11-27 06:33

    I have dealt with strip_tags function in PHP and had some problems like: after having a linebreak then appear a new line with some spaces and then a new linebreak appear continuously ...etc. without any rule :(.

    This is my solution for dealing with strip_tags

    Replace multiple spaces to one, multiple linebreaks to single linebreak

    function cleanHtml($html)
    {
        // Clean code into script tags
        $html = preg_replace('#(.*?)#is', '', $html);
    
        // Clean code into style tags
        $html = preg_replace('/<\s*style.+?<\s*\/\s*style.*?>/si', '', $html );
    
        // Strip HTML
        $string = trim(strip_tags($html));
    
        // Replace multiple spaces on each line (keep linebreaks) with single space
        $string = preg_replace("/[[:blank:]]+/", " ", $string); // (*)
    
        // Replace multiple spaces of all positions (deal with linebreaks) with single linebreak
        $string = preg_replace('/\s{2,}/', "\n", $string); // (**)
        return $string;
    }
    

    Keywords are (*) and (**).

提交回复
热议问题