How to replace one or two consecutive line breaks in a string?

后端 未结 3 1234
暖寄归人
暖寄归人 2020-12-01 23:55

I\'m developing a single serving site in PHP that simply displays messages that are posted by visitors (ideally surrounding the topic of the website). Anyone can post up to

相关标签:
3条回答
  • 2020-12-02 00:20

    \R is the system-agnostic escape sequence which will match \n, \r and \r\n.

    Because you want to greedily match 1 or 2 consecutive newlines, you will need to use a limiting quantifier {1,2}.

    Code: (Demo)

    $string = "Porcupines\nare\n\n\n\nporcupiney.";
    
    echo preg_replace('~\R{1,2}~', '<br />', $string);
    

    Output:

    Porcupines<br >are<br /><br />porcupiney.
    

    Now, to clarify why/where the other answers are incorrect...

    @DavidZ's unexplained answer fails to replace the lone newline character (Demo of failure) because of the incorrect quantifier expression.

    It generates:

    Porcupines\nare<br/><br/>porcupiney.
    

    The exact same result can be generated by @chaos's code-only answer (Demo of failure). Not only is the regular expression long-winded and incorrectly implementing the quantifier logic, it is also adding the s pattern modifier.

    The s pattern modifier only has an effect on the regular expression if there is a dot metacharacter in the pattern. Because there is no . in the pattern, the modifier is useless and is teaching researchers meaningless/incorrect coding practices.

    0 讨论(0)
  • 2020-12-02 00:24

    Something like

    preg_replace('/(\r|\n|\r\n){2,}/', '<br/><br/>', $text);
    

    should work, I think. Though I don't remember PHP syntax exactly, it might need some more escaping :-/

    0 讨论(0)
  • 2020-12-02 00:43
    preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/s', "\n\n", $text)
    
    0 讨论(0)
提交回复
热议问题