php 使用正则表达式删除多余的换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/816085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing redundant line breaks with regular expressions
提问by tevan
I'm developing a single serving sitein 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.
我正在用 PHP开发一个单一的服务站点,它只显示访问者发布的消息(最好围绕网站主题)。任何人每小时最多可以发布三条消息。
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.
由于网站只有一页,我想控制每条消息的垂直长度。但是,我确实希望至少部分保留原始消息中的换行符。妥协是允许两个换行符,但如果有两个以上,则用总共两个连续换行符替换它们。Stack Overflow 实现了这一点。
For example:
例如:
"Porcupines\nare\n\n\n\nporcupiney."
“豪猪\nare\n\n\n\n豪猪。”
would be changed to
将更改为
"Porcupines<br />are<br /><br />porcupiney."
“豪猪<br />是<br /><br />豪猪。”
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.
检查换行符的一个棘手方面是它们被收集并存储为 \r\n、\r 或 \n 的可能性。我想过使用 nl2br() 将所有换行符转换为 <br /> ,但这似乎没有必要。
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?
我的问题:在 PHP 中使用正则表达式(使用 preg_match() 和 preg_replace() 等函数),如何检查连续两个以上换行符的实例(它们之间有或没有空格),然后将它们更改为一共有两个换行符?
回答by chaos
preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/s', "\n\n", $text)
回答by David Z
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 :-/
应该工作,我想。虽然我不记得确切的 PHP 语法,但它可能需要更多的转义:-/

