views:

2982

answers:

2

Hello,

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?

+2  A: 
preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/s', "\n\n", $text)
chaos
Thank you chaos! That works exactly as desired. Your original response worked too.
tevan
Original response didn't meet your 'with or without blank space between them' criterion. :)
chaos
A: 

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 :-/

David Zaslavsky
Thanks David. The only issue I see with the regular expression you posted is that it doesn't accommodate spaces between line breaks.
tevan
Ah, true... I missed the part of your question where you mentioned spaces between line breaks.
David Zaslavsky