为什么我必须在单引号括起的字符串中转义双引号?

时间:2022-02-10 08:17:44

I have a variable which I set to an HTML tag (drop down menu):

我有一个变量,我设置为HTML标记(下拉菜单):

$weapon_secondary = '<select name="weapon" class="dropdown">
<option>Option 1</option>
<option>Option 2</option>
</select>'

Running my PHP file gives me

运行我的PHP文件给了我

Parse error: syntax error, unexpected 'weapon' (T_STRING) in C:\web\submit_build.php on line 437

解析错误:语法错误,第437行C:\ web \ submit_build.php中的意外“武器”(T_STRING)

As soon as I escape the double quotes, the parser works just fine. I thought strings in single quotes were taken 'as-is'? This code works just fine:

一旦我转义双引号,解析器就可以正常工作。我认为单引号中的字符串是“原样”的?这段代码很好用:

$weapon_secondary = '<select name=\"weapon\" class=\"dropdown\">
<option>Option 1</option>
<option>Option 2</option>
</select>'

Why do I have to escape double quotes within single ones?

为什么我必须在单个引号内转义双引号?

3 个解决方案

#1


0  

your error must be somewhere else.

你的错误必须在其他地方。

see working example : http://phpfiddle.org/main/code/m6g-25w

见工作实例:http://phpfiddle.org/main/code/m6g-25w

#2


0  

Looks like you are missing semicolon ; at the end of your variable assignment.

看起来你错过了分号;在变量赋值的末尾。

It should be:

它应该是:

$weapon_secondary = '<select name="weapon" class="dropdown">
<option>Option 1</option>
<option>Option 2</option>
</select>';

As an alternative you can use heredoc to declare a variable and avoid this quoting exercise:

作为替代方案,您可以使用heredoc声明变量并避免此引用练习:

$weapon_secondary <<< EOF
<select name="weapon" class="dropdown">
<option>Option 1</option>
<option>Option 2</option>
</select>
EOF;

#3


0  

You shouldn't, there must be some misconfiguration going on here. Make sure that Magic Quotes are disabled in your php.ini file.

你不应该,这里必须有一些错误的配置。确保在php.ini文件中禁用Magic Quotes。

#1


0  

your error must be somewhere else.

你的错误必须在其他地方。

see working example : http://phpfiddle.org/main/code/m6g-25w

见工作实例:http://phpfiddle.org/main/code/m6g-25w

#2


0  

Looks like you are missing semicolon ; at the end of your variable assignment.

看起来你错过了分号;在变量赋值的末尾。

It should be:

它应该是:

$weapon_secondary = '<select name="weapon" class="dropdown">
<option>Option 1</option>
<option>Option 2</option>
</select>';

As an alternative you can use heredoc to declare a variable and avoid this quoting exercise:

作为替代方案,您可以使用heredoc声明变量并避免此引用练习:

$weapon_secondary <<< EOF
<select name="weapon" class="dropdown">
<option>Option 1</option>
<option>Option 2</option>
</select>
EOF;

#3


0  

You shouldn't, there must be some misconfiguration going on here. Make sure that Magic Quotes are disabled in your php.ini file.

你不应该,这里必须有一些错误的配置。确保在php.ini文件中禁用Magic Quotes。