通过html元素属性内的php打印特殊字符 [英] Print special characters via php inside a html element's attribute
问题描述
假设 $ string =AXèdfdfdèsèdsè'/ \
(实际上,为 $ string
分配了此值数据库)
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>";
我得到输出,
<option \"'="" value="AX èdfdfdèsèdsè">AX èdfdfdèsèdsè'/\"</option>
如何正确地对此进行转义,以免创建其他无用的属性&而是获得与 $ string
中相同的值?
How can I properly escape this so that I don't create another useless attribute & instead get the same value as in $string
?
此外,Php无法逃脱<$的原因是什么?整个c $ c> $ string ?
Also, what is the reason Php does not escape $string
as a whole?
推荐答案
第二种用法应使用htmlspecialchars为了防止使用<破坏html,请使用$ string。在选项值引号内足以替换单引号:
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("'","'",$string)."'>".htmlspecialchars($string)."</option>";
输出为:
<option value='AX èdfdfdèsèdsè'/\"'>AX èdfdfdèsèdsè'/\"</option>
这篇关于通过html元素属性内的php打印特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!