Remove excessive line returns

后端 未结 5 1510
野的像风
野的像风 2021-01-13 09:12

I am looking for something like trim() but for within the bounds of a string. Users sometimes put 2, 3, 4, or more line returns after they type, I need to sanitize this inp

相关标签:
5条回答
  • 2021-01-13 09:42

    To consider all three line break sequences:

    preg_replace('/(?:\r\n|[\r\n]){2,}/', "\n\n", $str)
    
    0 讨论(0)
  • 2021-01-13 09:47

    Finally managed to get it, needs preg so you are using the PCRE version in php, and also needs a \n\n replacement string, in order to not wipe all line endings but one:

      $body = preg_replace("/\n\n+/", "\n\n", $body);
    

    Thanks for getting me on the right track.

    0 讨论(0)
  • 2021-01-13 09:50

    How much text do you need to do this on? If it is less than about 100k then you could probably just use a simple search and replace regex (searching something like /\n+/ and replace with \n)

    On the other hand if you need to go through megabytes of data, then you could parse the text character by character, copying the input to the output, except when mulitple newlines are encountered, in which case you would just copy one newline and ignore the rest.

    I would not recommend a recursive string replace though, sounds like that would be very very slow.

    0 讨论(0)
  • 2021-01-13 09:50

    The following regular expression should remove multiple linebreaks while ignoring single line breaks, which are okay by your definition:

    ereg_replace("\n\n+", "\n\n", $string);
    

    You can test it with this PHP Regular Expression test tool, which is very handy (but as it seems not in perfect parity with PHP).

    [EDIT] Fixed the ' to ", as they didn't seem to work. Have to admit I just tested the regex in the web tool. ;)

    0 讨论(0)
  • 2021-01-13 09:59
    function str_squeeze($body) {
        return preg_replace("/\n\n+/", "\n\n", $body);
    }
    
    0 讨论(0)
提交回复
热议问题