使用 htmlspecialchars 和 htmlentities 转换特殊字符
我现在对向数据库中注入特殊字符感到困惑...
例如,我想接受像这样的字符 ö
、ù
等,并且我想显示它们因为它们在 html 上,例如 Löic
,这是一个法语名称。
我认为在将这些特殊字符注入数据库之前我必须将它们转换为 html 实体,例如 ö
代表 ö
。
如果我使用 htmlspecialchars()
来转换它们,
Array
(
[name] => Löic
)
if(isset($_POST['name'])) $name = preg_replace('/\s\s+/', ' ', trim($_POST['name']));
$name = htmlspecialchars($name, ENT_QUOTES);
那么它应该转换成这个 Löic
但它根本没有转换,而是原样,
Löic
所以这是我检查数据库时得到的结果,它存储为,
Löic
如果我使用 htmlentities()
来转换它们,
$name = htmlentities($name, ENT_QUOTES);
那么我得到这个,
Löic
并且它在我的 html 上显示为这个,
Löic
为什么它这样做?我的头要爆炸了!我不知道问题出在哪里。请帮忙...我该怎么做才能使它正确?
这与我在名称列中设置的 utf8_general_ci
有关吗?
谢谢。
I am getting confused with injecting special characters into my database now...
For instance, I want to accept characters like this ö
, ù
, etc and I want to display them as they are on html such as Löic
which is a French name.
And I thought I must convert these special characters into html entities before injecting them into database, like ö
for ö
.
If I use htmlspecialchars()
to convert them,
Array
(
[name] => Löic
)
if(isset($_POST['name'])) $name = preg_replace('/\s\s+/', ' ', trim($_POST['name']));
$name = htmlspecialchars($name, ENT_QUOTES);
So it should be converted into this Löic
but it is not converted at all, instead as it is,
Löic
So this is what I get when I check my database, it is stored as,
Löic
If I use htmlentities()
to convert them,
$name = htmlentities($name, ENT_QUOTES);
then I get this,
Löic
and it is displayed as this on my html,
Löic
Why does it do that?? My head is going to explode! I don't know where the problem is. Please help... What shall I do to make it right?
Is it to do with utf8_general_ci
which I set at that name column??
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
发生这种情况是因为您尝试使用 htmlentites 转换 utf8 字符。遗憾的是,该函数只能正确地处理 ascii 字符。最简单的解决方案是将字符串简单存储在 utf8 数据库表中,并仅使用 htmlspecialchars 而不是 htmlentities 输出它们。请务必将页面编码设置为 utf8。
This happens because you are trying to convert utf8 characters with htmlentites. Sadly the function does only work on ascii chars correctly. The easiest solution is to simple store your strings in your utf8 database table and output them with only htmlspecialchars instead of htmlentities. Just be sure to set your page encoding to utf8.
您也可以简单地执行以下操作:
Also you can simple do: