如何输出一个字符串,其中的换行符在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?
我有一个字符串,其中包含我想打印的换行符,以便我看到特殊字符(例如 所以一个字符串通常是 看起来像这样:
我怎么能 在PHP中完成这个? p>
div>
code>)而不是换行符本身。 p>
echo code>'d as p> \ n
这是我的字符串的第一行
这是字符串的第二行
code> pre>
这是我的字符串的第一行
这是字符串的第二行
code> pre>
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