如何输出一个字符串,其中的换行符在php中可见?

I have a string with newlines that I'd like to print out so that I see the special chars (such as ) 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
this is the second line of the string

How could I accomplish this in php?

Try this:

<?php

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

echo json_encode($string);

?>

You can use the addcslashes function:

string addcslashes ( string $str , string $charlist )

which will return a string with backslashes before characters.

One way to achieve this is

echo str_replace("
", '
', $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