从字符串中删除新行,并用一个空格替换 [英] Remove new lines from string and replace with one empty space

查看:86
本文介绍了从字符串中删除新行,并用一个空格替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$string = "
put returns between paragraphs

for linebreak add 2 spaces at end

";

想要从字符串中删除所有新行.

Want to remove all new lines from string.

我有这个正则表达式,它可以捕获所有正则表达式,问题是我不知道应该使用哪个函数.

I've this regex, it can catch all of them, the problem is I don't know with which function should I use it.

/\r\n|\r|\n/

$string应该变为:

$string = "put returns between paragraphs for linebreak add 2 spaces at end ";

推荐答案

您必须对双换行符保持谨慎,因为换行符会引起双倍空格.使用这个非常有效的正则表达式:

You have to be cautious of double line breaks, which would cause double spaces. Use this really efficient regular expression:

$string = trim(preg_replace('/\s\s+/', ' ', $string));

多个空格和换行符替换为一个空格.

Multiple spaces and newlines are replaced with a single space.

正如其他人指出的那样,该解决方案存在单词之间匹配单个换行符的问题.这个例子中没有,但是可以很容易地看出这种情况是如何发生的.一种替代方法是执行以下操作:

As others have pointed out, this solution has issues matching single newlines in between words. This is not present in the example, but one can easily see how that situation could occur. An alternative is to do the following:

$string = trim(preg_replace('/\s+/', ' ', $string));

这篇关于从字符串中删除新行,并用一个空格替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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