我使用此代码来生成html
echo "<input type='button' onclick=\"myFunc('$param');\" />";
Run Code Online (Sandbox Code Playgroud)
除非$ param包含'或"字符,否则一切都会好的.如何处理这些情况?
PS.当用户输入时,mysql_real_escape_string($ param)将无法正常工作".
有几个功能可以使用:
<?php
$string = 'string test"';
echo htmlentities($string) . "\n";
echo addslashes($string) . "\n";
Run Code Online (Sandbox Code Playgroud)
他们产生以下内容:
string test"
string test\"
Run Code Online (Sandbox Code Playgroud)
正如达米安所说;使用Addslashes :)
$param=addslashes($param);
echo "<input type='button' onclick=\"myFunc('$param');\" />";
Run Code Online (Sandbox Code Playgroud)
如果您依赖用户输入,请使用 htmlentities($param, ENT_QUOTES);
参见http://uk.php.net/manual/en/function.htmlentities.php
首先做
// 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