Reputation: 45
when i try
echo "anything \n whatever";
the result :
anything
whatever
But when i try it from user input it doesn't work
test.php
<html>
<body>
<h1>Authentication v 0.04</h1>
<form action="" method="GET">
Login <br/>
<input type="text" name="username" /><br/><br/>
<input type="submit" value="connect" /><br/><br/>
</form>
<fieldset><legend>Authentication log</legend><pre>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
echo $_GET['username'];
?>
</pre></fieldset></body></html>
if $_GET['username'] = "anything \n whatever"
the result is
"anything \n whatever"
it treats \n
as string !!!
why ?
Upvotes: 1
Views: 400
Reputation: 4265
\n
is an escape sequence which represents an end of line [1]. An escape sequence only makes sense on PHP interpolation (i.e. double quotes).
In HTML \n
has no special meaning so it is printed as a string. [2]
If there is an actual new line, you may want to use the nl2br
function (http://php.net/manual/en/function.nl2br.php) to automatically convert any \n
to a <br>
tag.
If you want to convert any literal \n
to <br>
, you may want to use a str_replace
function (http://php.net/manual/en/function.str-replace.php) for example like this:
echo str_replace ('\n', '<br>', $_GET['username']);
Notice the single quotes to avoid further interpolation.
[1] In fact, it is a new line only on *nix systems, while it's different on Microsoft and old Mac OSx. You may want to take a look at PHP_EOL
constant (http://php.net/manual/en/reserved.constants.php).
[2] In fact, it is printed as a new line in the HTML source, which is a text file.
Upvotes: 2
Reputation: 96258
Escape sequences are only interpreted in double quoted strings in the PHP source (well, you can escape \'
in single quoted strings, but that's not relevant here).
When you type \n
in the browser, that's literally two characters, \
and n
.
Upvotes: 1