PHP- \ n不起作用

时间:2016-06-05 20:46:14

标签: php

当我尝试

anything

whatever

结果:

<html>
    <body>
    <h1>Authentication v 0.04</h1>
    <form action="" method="GET">
     Login&nbsp;<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>

但是当我从用户输入尝试它时它不起作用

test.php的

$_GET['username'] = "anything \n whatever"

如果"anything \n whatever"

结果是

\n

它将unarchive视为字符串!!!

为什么?

2 个答案:

答案 0 :(得分:2)

\n是一个表示行尾[1]的转义序列。转义序列仅对PHP插值有意义(即双引号)。

在HTML \n中没有特殊含义,因此它打印为字符串。 [2]

如果有实际的新行,您可能需要使用nl2br函数(http://php.net/manual/en/function.nl2br.php)自动将任何\n转换为<br>代码。

如果您想将任何文字\n转换为<br>,您可能需要使用str_replace函数(http://php.net/manual/en/function.str-replace.php),例如:

echo str_replace ('\n', '<br>', $_GET['username']);

注意单引号以避免进一步插值。

[1]事实上,它只是* nix系统上的一个新系列,而它在微软和旧的Mac OSx上有所不同。您可能需要查看PHP_EOL常量(http://php.net/manual/en/reserved.constants.php)。

[2]事实上, 打印为HTML 来源中的新行,这是一个文本文件。

答案 1 :(得分:1)

转义序列仅在PHP源代码中用双引号字符串解释(好吧,你可以在单引号字符串中转义\',但这里不相关)。

在浏览器中输入\n时,实际上只有两个字符\n