0

我对在 php 中使用 java 脚本和 html 标签时使用单引号和双引号以及反斜杠感到困惑,任何人都可以澄清一下,我用谷歌搜索了它,但仍然不清楚。我对这个小东西感到困惑。我是编程新手 - 这是我的代码

 <?php
if(isset($_GET['id'])) {
echo '<div id="d2">';
include "test2.php";
 echo '</div>'; }
 else
 { 
  echo '<div id="d1">';
 include "insert.php";
 print "<script type=javascript>"
 print "document.getEelementById('alertdiv1').innerHTML='hi' ;"
 print "</script>"
echo '</div>';
     }
?>
4

5 回答 5

1

我在您的代码中看不到与引号相关的任何问题。

<script type=javascript>— 这不是 type 属性的有效值(现在无论如何都是可选的)。摆脱类型属性。

document.getEelementById— 元素中只有 3 个 es,而不是 4 个。

alertdiv1— 您的代码中没有具有该 id 的元素

于 2013-02-01T11:43:23.293 回答
1

在 PHP 中,您可以用单引号或双引号将字符串括起来。两者都有效:

$var = "this is a string";
$var2 = 'this is also a string';

主要区别在于,如果您的字符串包含变量,并且您希望变量内容被视为字符串的一部分,则需要使用双引号:

echo "$var which I made";

将返回:

这是我制作的字符串

当您操作 html、css 和 JavaScript 字符串时,您需要确保不会意外关闭您的 PHP 字符串。例如:

echo "<h1 class='myheading'>Heading Text</h1>";

请注意我是如何使用双引号将字符串括起来的?因为我这样做了,所以我能够在 html 中使用单引号,而无需转义它们。

如果我想在我的字符串中使用双引号,我将不得不转义它们,如下所示:

echo "<h1 class=\"myheading\">Heading Text</h1>";

告诉 PHP 紧随其后的\双引号将被视为文字,而不是用于终止字符串。

于 2013-02-01T11:43:44.023 回答
0

嗨,就单引号和双引号而言,当它是一个字符串时并不重要。但是当你在里面使用任何变量时

$a = 'hi';
echo '$a' ;

将输出

$a

但是当你使用“”

$a = 'hi';
    echo "$a" ;

它会打印

hi
于 2013-02-01T11:42:33.013 回答
0

基本上,如果您使用“”(引号)作为分隔符,然后使用引号作为字符串的一部分,则必须通过在其前面放置反斜杠来对其进行转义。

例如:

$string = "This is my string"; // This is fine as the value of the string doesn't contain any quotation marks (")

$string = "I am including a quote in my string \"To Be Or Not To Be\"."; // This is also fine, as I have escaped the quotation marks inside the string

如果您使用 ''(撇号)作为分隔符,然后又想将它们用作字符串的一部分,则同样适用,您必须使用反斜杠 () 对它们进行转义。

希望有帮助。

于 2013-02-01T11:45:53.437 回答
0

$var = "AAA";
echo '这要花费很多 $var.'; // 这会花费很多 $s。
echo "这要花很多 $var."; // 这要花很多 AAA。

于 2013-02-01T11:56:23.427 回答