双引号在PHP脚本echo中的使用

22

我有一行 PHP 代码看起来像这样:

echo "<script>$('#edit_errors').html('<h3><em>Please Correct Errors Before Proceeding</em></h3>')</script>";

我想知道如何正确地为文本添加字体颜色。 如果我这样做:

echo "<script>$('#edit_errors').html('<h3><em><font color="red">Please Correct Errors Before Proceeding</font></em></h3>')</script>";

单词 "red" 用黑色字体写出来,编译器会报错。

如果我使用单引号将 "red" 括起来,文本将根本不会显示。

任何帮助都将不胜感激。谢谢。

6个回答

66

您需要对"进行转义,这样它就不会被解释为字符串的结束符。使用\来对其进行转义:

echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";

阅读更多:字符串转义序列


13

可以使用HEREDOC,这样就不需要更改引号类型或对其进行转义:

echo <<<EOL
<script>$('#edit_errors').html('<h3><em><font color="red">Please Correct Errors Before Proceeding</font></em></h3>')</script>
EOL;

4

只需转义您的引号:

echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";

3

你需要在字符串中添加反斜杠\来转义引号"

例如:

"<font color=\"red\">"

如何编写 < 或 > 字符。由于编写它们会分别更改为 < 和 > :( - Aada

2

如果您需要在echo语句中访问变量,请将变量放置在花括号内。

echo "i need to open my lock with its: {$array['key']}";

这不是OP所问的。 - Gui Imamura

1
您可以忽略字母数字属性的引号:
echo "<font color=red> XHTML is not a thing anymore. </font>";
echo "<div class=editorial-note> There, I said it. </div>";

这在HTML中是完全有效的,尽管仍然不受欢迎,但自HTML5以来绝对很流行。

注意事项


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接