通过html元素属性内的php打印特殊字符 [英] Print special characters via php inside a html element's attribute

查看:90
本文介绍了通过html元素属性内的php打印特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设 $ 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 \&quot;'="" 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("'","&#039;",$string)."'>".htmlspecialchars($string)."</option>";

输出为:

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

这篇关于通过html元素属性内的php打印特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆