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

问题描述

$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.

/
|
|
/

$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('/ss+/', ' ', $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));

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

08-21 00:34