如何替换字符串中的一两个连续换行符? [英] How to replace one or two consecutive line breaks in a string?

查看:55
本文介绍了如何替换字符串中的一两个连续换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用PHP开发一个单个服务站点访问者发布的消息(最好是围绕网站主题).任何人每小时最多可以发布三则消息.

由于该网站只有一页,所以我想控制每封邮件的垂直长度.但是,我确实希望至少部分保留原始消息中的换行符.一种折衷方法是允许两个换行符,但是如果有两个以上的换行符,则将它们换成总共连续两个换行符.堆栈溢出实现了这一点.

例如:

 豪猪\ nare \ n \ n \ n \ n豪猪. 

将更改为

豪猪
是豪猪.

检查换行符的一个棘手的方面是它们是否可能被收集并存储为 \ r \ n \ r \ n .我曾考虑过使用 nl2br()将所有换行符转换为< br/> ,但这似乎是不必要的.

我的问题:在PHP中使用正则表达式(具有诸如 preg_match() preg_replace()之类的函数),如何检查两个以上换行符的实例排成一行(它们之间有无空格),然后将它们更改为总共两个换行符?

解决方案

  preg_replace('/(?:(?:(?:\ r \ n | \ r | \ n)\ s *){2}/s',"\ n \ n",$ text) 

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)

这篇关于如何替换字符串中的一两个连续换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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