Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape double quotes with variable inside HTML echo [duplicate]

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']."
like image 215
swiftsly Avatar asked Dec 16 '13 22:12

swiftsly


People also ask

How do you escape a double quote in HTML?

The escape code &#34; can also be used instead of &quot; . Show activity on this post. Using &quot; is the way to do it.

How do you escape a double quote in a string?

Double Quotes inside verbatim strings can be escaped by using 2 sequential double quotes "" to represent one double quote " in the resulting string. var str = @"""I don't think so,"" he said. "; Console. WriteLine(str);

Can you use double quotes in double quotes escape characters?

To include double quotes inside a formula, you can use additional double quotes as escape characters. By escaping a character, you are telling Excel to treat the " character as literal text. You'll also need to include double quotes wherever you would normally in a formula.

How do you escape quotes in HTML?

JavaScript Strings Escaping quotes Quotes in HTML strings can also be represented using &apos; (or &#39; ) as a single quote and &quot; ( or &#34; ) as double quotes. Note: The use of &apos; and &quot; will not overwrite double quotes that browsers can automatically place on attribute quotes.


2 Answers

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
like image 181
Ja͢ck Avatar answered Oct 05 '22 09:10

Ja͢ck


Use htmlentities:

echo "<input type=\"hidden\" name=\"id\" value=\"".htmlentities($row['id'])."\" />";
like image 22
elixenide Avatar answered Oct 05 '22 11:10

elixenide