Print special characters via php inside a html ele

2019-07-20 04:02发布

问题:

Assume $string = AX èdfdfdèsèdsè'/\" (actually, $string is assigned this value from the DB)

So when I print the following,

echo "<option value='". htmlspecialchars($string) ."'>".$string."</option>";

I get the output,

<option \&quot;'="" value="AX èdfdfdèsèdsè">AX èdfdfdèsèdsè'/\"</option>

How can I properly escape this so that I don't create another useless attribute & instead get the same value as in $string?

Also, what is the reason Php does not escape $string as a whole?

回答1:

You should use htmlspecialchars on the second usage of $string in order to prevent breaking the html with a "<". Inside of the option value quotes it is sufficient to replace the single quotes:

echo "<option value='".str_replace("'","&#039;",$string)."'>".htmlspecialchars($string)."</option>";

Output is:

<option value='AX èdfdfdèsèdsè&#039;/\"'>AX èdfdfdèsèdsè'/\&quot;</option>


回答2:

An alternate answer would be using htmlspecialchars($value,ENT_QUOTES) So basically that would be

echo "<option value='". htmlspecialchars($value,ENT_QUOTES)."'>".($value)."</option>";

It seems that neither htmlspecialchars($value) nor htmlentities($value) convert single-quotes ' by default unless explicitly setting the ENT_QUOTES flag.



回答3:

echo '<option value="', htmlspecialchars($string), '">', htmlspecialchars($string), '</option>';

PHP doesn't escape anything unless you tell it to. ;)