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

后端 未结 3 1243
暖寄归人
暖寄归人 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}~', '
    ', $string);

    Output:

    Porcupines
    are

    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

    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.

提交回复
热议问题