如何加倍所有换行符?

时间:2022-09-15 15:44:24

Edit: The problem described below was just caused by a "feature" of my IDE, so there's actually nothing wrong with the regex. If you're interested in how to double line breaks, here's your question and answer in one neat package. :)

编辑:下面描述的问题只是由我的IDE的“功能”引起的,因此正则表达式实际上没有任何问题。如果您对如何加倍换行感兴趣,请在一个整齐的包中找到您的问题和答案。 :)

I want to change every line break in a string to be two line breaks:

我想将字符串中的每个换行符更改为两个换行符:

"this is
an example
string"
// becomes:
"this is

an example

string"

However, it needs to take Unix/Windows line endings into account. I've written the code below, but it's not behaving itself.

但是,它需要考虑Unix / Windows行结尾。我已经编写了下面的代码,但它并没有表现出来。

$output = preg_replace("/(\r?\n)/", "$1$1", $input);

But it's not working. Changing the replacement string to this...

但它不起作用。将替换字符串更改为此...

"$1 $1"

...makes it work, but then I have an unwanted space in between.

...使它工作,但我之间有一个不需要的空间。

2 个解决方案

#1


That's interesting. I just tested your sample code on two different UNIX systems (Ubuntu and a FreeBSD box, for the record). In both cases, it worked exactly as you say you wish it to. So your platform or your configuration may be partially at fault.

那很有意思。我刚刚在两个不同的UNIX系统上测试了您的示例代码(Ubuntu和一个FreeBSD框,用于记录)。在这两种情况下,它的工作方式与您希望的完全一样。因此,您的平台或配置可能部分有问题。

#2


Wait Wait. Are you just directly outputting that to the browser? Did you View Source? Returns are not shown in HTML. Try putting <pre> before and </pre> after, if you want to view the returns as line breaks.

等等。你只是直接将其输出到浏览器?你看过来源了吗?返回不以HTML格式显示。如果要将返回视为换行符,请尝试将

放在
之前和
  
  之后。

#1


That's interesting. I just tested your sample code on two different UNIX systems (Ubuntu and a FreeBSD box, for the record). In both cases, it worked exactly as you say you wish it to. So your platform or your configuration may be partially at fault.

那很有意思。我刚刚在两个不同的UNIX系统上测试了您的示例代码(Ubuntu和一个FreeBSD框,用于记录)。在这两种情况下,它的工作方式与您希望的完全一样。因此,您的平台或配置可能部分有问题。

#2


Wait Wait. Are you just directly outputting that to the browser? Did you View Source? Returns are not shown in HTML. Try putting <pre> before and </pre> after, if you want to view the returns as line breaks.

等等。你只是直接将其输出到浏览器?你看过来源了吗?返回不以HTML格式显示。如果要将返回视为换行符,请尝试将

放在
之前和
  
  之后。