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 three messages an hour.
Since the website will only be one page, I'd like to control the vertical length of each message. However, I do want to at least partially preserve line breaks in the original message. A compromise would be to allow for two line breaks, but if there are more than two, then replace them with a total of two line breaks in a row. Stack Overflow implements this.
For example:
Porcupines\nare\n\n\n\nporcupiney.
would be changed to
Porcupines<br />are<br /><br />porcupiney.
One tricky aspect of checking for line breaks is the possibility of their being collected and stored as \r\n
, \r
, or \n
. I thought about converting all line breaks to <br />
s using nl2br()
, but that seemed unnecessary.
My question: Using regular expressions in PHP (with functions like preg_match()
and preg_replace()
), how can I check for instances of more than two line breaks in a row (with or without blank space between them) and then change them to a total of two line breaks?
preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/s', "\n\n", $text)