Replace multiple newlines, tabs, and spaces

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

    ' . preg_replace(array('/(\r\n\r\n|\r\r|\n\n)(\s+)?/', '/\r\n|\r|\n/'), array('

    ', '
    '), $text) . '

    '; }

提交回复
热议问题