Henrik Petterson
Henrik Petterson

Reputation: 7094

Replace single line break with double line break

I have a string:

$str =
'hello
world';

And I want to replace single line breaks to double line breaks, so we have:

$str =
'hello

world';

I tried:

$str = str_replace("\n", "\n\n", $str);

But it did not work. What's the correct approach? Can we use PHP_EOL...?

Upvotes: 2

Views: 150

Answers (2)

splash58
splash58

Reputation: 26153

To don't think about EOL format, you can use regex to find and clone it. \R works with any EOL char combination

$str = preg_replace("/(\R)/", "$1$1", $str);

demo

Upvotes: 2

Rinsad Ahmed
Rinsad Ahmed

Reputation: 1933

You approach is working but you need an plain/text output header to see it working on the browser.

header('Content-Type:text/plain');

Upvotes: 0

Related Questions