开始PhP:保护引号


Beginning PhP: to protect quotes

我是PhP n00b。我正在阅读一些在线教程,但我已经有一个问题(我想这是一个非常基本的问题):

我不明白为什么以下代码能正常工作:

<html>
    <head>
        <title> My Firts PHP page </title>
    </head>
    <body>
        <?php
            $userAgent = $_SERVER["HTTP_USER_AGENT"];
            echo "<p>This is my awesome User Agent: <b>'"$userAgent'"</b></p>";
        ?>
    </body>
</html>

相反,尽管我保护了括号内的引号,但以下内容不起作用:

<html>
    <head>
        <title> My Firts PHP page </title>
    </head>
    <body>
        <?php
            echo "<p>This is my awesome User Agent: <b>$_SERVER['"HTTP_USER_AGENT'"]</b></p>";
        ?>
    </body>
</html>

提前谢谢。

您基本上已经找到了字符串插值的边缘情况。虽然字母数字数组键需要在PHP中引用,但在双引号字符串中,它们需要不加引号

echo "<p>This is my awesome User Agent: <b>$_SERVER[HTTP_USER_AGENT]</b></p>";

字符串解析遵循自己的规则。通常,您不能将随机的PHP代码放入字符串中并执行它。

您可以尝试其中一种:

花括号允许字符串中的复杂表达式

<html>
    <head>
        <title> My Firts PHP page </title>
    </head>
    <body>
        <?php
            echo "<p>This is my awesome User Agent: <b>{$_SERVER['"HTTP_USER_AGENT'"]}</b></p>";
        ?>
    </body>
</html>

更好的是,只需对输出的部分使用php。

<html>
    <head>
        <title> My Firts PHP page </title>
    </head>
    <body>
        <p>This is my awesome User Agent: <b><?php echo $_SERVER["HTTP_USER_AGENT"]; ?></b></p>
    </body>
</html>

转义引号的错误用法。查看并测试:

echo "<p>This is my awesome User Agent: <b>". $_SERVER["HTTP_USER_AGENT"] ."</b></p>";

您可以在字符串中包含一个变量,如下所示:

echo "<p>This is my awesome User Agent: <b>{$_SERVER["HTTP_USER_AGENT"]}</b></p>";

如果你使用,它会更好、更干净

echo "<p>This is my awesome User Agent: <b>". $_SERVER["HTTP_USER_AGENT"] ."</b></p>";

或者数组密钥中没有单引号

echo "<p>This is my awesome User Agent: <b>$_SERVER[HTTP_USER_AGENT]</b></p>";