Escape double quotes with variable inside HTML echo [duplicate]

时光总嘲笑我的痴心妄想 提交于 2019-11-27 04:49:11

问题


This question already has an answer here:

  • Single and double quotes together as HTML attribute value? 2 answers

For a variable inside a echo that contains HTML, where would I add slashes to escape the double quotes?

Example:

echo "<input type=\"hidden\" name=\"id\" value=".$row['id']." />";

This part:

value=".$row['id']."

回答1:


Some tips on outputting HTML with PHP:

  1. Use single quotes so that you don't have to escape the double quotes (when using echo),
  2. Use htmlspecialchars() to properly escape any "rogue" values you may have.

Example using echo:

echo '<input type="hidden" name="id" value="', htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8'), '" />';

Or printf():

printf('<input type="hidden" name="id" value="%s" />', 
    htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8')
);

Or, in HTML mode:

?>
<input type="hidden" name="id" value="<?php echo htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8'); ?>" />
<?php



回答2:


Use htmlentities:

echo "<input type=\"hidden\" name=\"id\" value=\"".htmlentities($row['id'])."\" />";



回答3:


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'].'" />';


来源:https://stackoverflow.com/questions/20622676/escape-double-quotes-with-variable-inside-html-echo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!