Replace multiple newlines, tabs, and spaces

前端 未结 10 1787
情深已故
情深已故 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:43

    Replace the head and the end of string or document!

    preg_replace('/(^[^a-zA-Z]+)|([^a-zA-Z]+$)/','',$match);
    
    0 讨论(0)
  • 2020-11-27 06:52

    You need the multiline modifier to match multiple lines:

    preg_replace("/PATTERN/m", "REPLACE", $text);
    

    Also in your example you seem to be replacing 2+ newlines with exactly 2, which isn't what your question indicates.

    0 讨论(0)
  • 2020-11-27 06:55

    This is the answer, as I understand the question:

    // Normalize newlines
    preg_replace('/(\r\n|\r|\n)+/', "\n", $text);
    // Replace whitespace characters with a single space
    preg_replace('/\s+/', ' ', $text);
    

    This is the actual function that I use to convert new lines to HTML line break and paragraph elements:

    /**
     *
     * @param string $string
     * @return string
     */
    function nl2html($text)
    {
        return '<p>' . preg_replace(array('/(\r\n\r\n|\r\r|\n\n)(\s+)?/', '/\r\n|\r|\n/'),
                array('</p><p>', '<br/>'), $text) . '</p>';
    }
    
    0 讨论(0)
  • 2020-11-27 06:58

    I would suggest something like this:

    preg_replace("/(\R){2,}/", "$1", $str);
    

    This will take care of all the Unicode newline characters.

    0 讨论(0)
提交回复
热议问题