使用正则表达式删除冗余换行符 [英] Removing redundant line breaks with regular expressions

查看:142
本文介绍了使用正则表达式删除冗余换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在PHP中开发单一服务网站,只需显示消息由访问者发布(理想地围绕网站的主题)。任何人每小时最多可以发送三条消息。

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.

例如:

Porcupines\\\
are\\\
\\\
\\ \\ n \\\
porcupiney。

"Porcupines\nare\n\n\n\nporcupiney."

将更改为

豪猪< br />是/>< br /> porcupiney。

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

检查换行符的一个棘手的方面是将其收集并存储为\\\
的可能性, \r或\\\
。我想到使用nl2br()将所有换行符转换为< br /> s,但这似乎是不必要的。

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.

我的问题:在PHP中使用正则表达式像preg_match()和preg_replace()),如何检查一行中有多于两个换行符的实例(有或没有空格间),然后将它们更改为总共两个换行符?

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)

这篇关于使用正则表达式删除冗余换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆