php 使用 HTML echo 中的变量转义双引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20622676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Escape double quotes with variable inside HTML echo
提问by swiftsly
For a variable inside a echo that contains HTML, where would I add slashes to escape the double quotes?
对于包含 HTML 的 echo 中的变量,我应该在哪里添加斜杠来转义双引号?
Example:
例子:
echo "<input type=\"hidden\" name=\"id\" value=".$row['id']." />";
This part:
这部分:
value=".$row['id']."
回答by Ja?ck
Some tips on outputting HTML with PHP:
使用 PHP 输出 HTML 的一些技巧:
- Use single quotes so that you don't have to escape the double quotes (when using echo),
- Use
htmlspecialchars()to properly escape any "rogue" values you may have.
- 使用单引号,这样您就不必转义双引号(使用 echo 时),
- 使用
htmlspecialchars()正确逃生你可能有任何“流氓”的价值观。
Example using echo:
使用示例echo:
echo '<input type="hidden" name="id" value="', htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8'), '" />';
Or printf():
或者printf():
printf('<input type="hidden" name="id" value="%s" />',
htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8')
);
Or, in HTML mode:
或者,在 HTML 模式下:
?>
<input type="hidden" name="id" value="<?php echo htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8'); ?>" />
<?php
回答by elixenide
Use htmlentities:
使用htmlentities:
echo "<input type=\"hidden\" name=\"id\" value=\"".htmlentities($row['id'])."\" />";
回答by Bryan Elliott
How about use single quotes so you don't have to escape any quotes. Like so:
如何使用单引号,这样您就不必转义任何引号。像这样:
echo '<input type="hidden" name="id" value="'.$row['id'].'" />';

