johncorser
johncorser

Reputation: 9822

How can I output a string with it's newline characters visible in php?

I have a string with newlines that I'd like to print out so that I see the special chars (such as \n) rather than the newlines themselves.

So a string that would typically be echo'd as

this is the top line of my string
this is the second line of the string

Would instead look like this:

this is the top line of my string\nthis is the second line of the string

How could I accomplish this in php?

Upvotes: 0

Views: 2930

Answers (3)

alariva
alariva

Reputation: 2139

One way to achieve this is

echo str_replace("\n", '\n', $yourstring);

Of course, there are many other ways and you can assign instead of echoing, and enhance your code so on.

Consider that new lines might be treated differently according to the underlaying operating system.

also consider reading the theorical background about new line and carrier return

Upvotes: 1

NorthernLights
NorthernLights

Reputation: 370

Try this:

<?php

$string = "this is the top line of my string
this is the second line of the string";

echo json_encode($string);

?>

Upvotes: 4

user4628565
user4628565

Reputation:

You can use the addcslashes function:

string addcslashes ( string $str , string $charlist )

which will return a string with backslashes before characters.

Upvotes: 1

Related Questions