使用PHP转义变量中的引号

Ale*_*der 5 javascript php

我使用此代码来生成html

echo "<input type='button' onclick=\"myFunc('$param');\" />";
Run Code Online (Sandbox Code Playgroud)

除非$ param包含'"字符,否则一切都会好的.如何处理这些情况?

PS.当用户输入时,mysql_real_escape_string($ param)将无法正常工作".

Nic*_*ick 9

有几个功能可以使用:

<?php
$string = 'string test"';

echo htmlentities($string) . "\n";
echo addslashes($string) . "\n";
Run Code Online (Sandbox Code Playgroud)

他们产生以下内容:

string test&quot;
string test\"
Run Code Online (Sandbox Code Playgroud)


mis*_*koz 5

正如达米安所说;使用Addslashes :)

$param=addslashes($param);
echo "<input type='button' onclick=\"myFunc('$param');\" />";
Run Code Online (Sandbox Code Playgroud)


jba*_*sko 5

如果您依赖用户输入,请使用 htmlentities($param, ENT_QUOTES);

参见http://uk.php.net/manual/en/function.htmlentities.php


diE*_*cho 1

首先做

// only for the GUY who didn't read the complete answer :(
$param=addslashes($param); 
Run Code Online (Sandbox Code Playgroud)

然后用简单的 HTML 编写代码

<input type='button' onclick="myFunc(<?php echo $param?>);" />
Run Code Online (Sandbox Code Playgroud)

注意: mysql_real_escape_string当我们使用 mysqltry 处理时有效addslashes

  • 如果 $param 包含`"`或`'`,您的代码示例有何帮助? (3认同)