替换多个换行符,制表符和空格 [英] Replace multiple newlines, tabs, and spaces

查看:101
本文介绍了替换多个换行符,制表符和空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个换行符替换多个换行符,并用一个空格替换多个空格.

I want to replace multiple newline characters with one newline character, and multiple spaces with a single space.

我尝试了preg_replace("/\n\n+/", "\n", $text);并失败了!

我也在$ text上执行此操作以进行格式化.

I also do this job on the $text for formatting.

$text = wordwrap($text, 120, '<br/>', true);
$text = nl2br($text);

$ text是从用户那里获取的用于BLOG的大文本,为了获得更好的格式,我使用了自动换行.

$text is a large text taken from user for BLOG, and for a better formatting I use wordwrap.

推荐答案

理论上,您的正则表达式确实有效,但问题是,并非所有操作系统和浏览器都仅在字符串末尾发送\ n.许多人还会发送\ r.

In theory, you regular expression does work, but the problem is that not all operating system and browsers send only \n at the end of string. Many will also send a \r.

尝试:

我简化了这个:

preg_replace("/(\r?\n){2,}/", "\n\n", $text);

要解决仅发送\ r的问题:

And to address the problem of some sending \r only:

preg_replace("/[\r\n]{2,}/", "\n\n", $text);

基于您的更新:

// Replace multiple (one ore more) line breaks with a single one.
$text = preg_replace("/[\r\n]+/", "\n", $text);

$text = wordwrap($text,120, '<br/>', true);
$text = nl2br($text);

这篇关于替换多个换行符,制表符和空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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