使用htmlspecialchars和htmlentities转换特殊字符 [英] Converting special characters with htmlspecialchars and htmlentities

查看:107
本文介绍了使用htmlspecialchars和htmlentities转换特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在对在数据库中插入特殊字符感到困惑...

I am getting confused with injecting special characters into my database now...

例如,我想接受诸如öù等的字符,并且希望以html之类的字符显示它们,例如Löic,这是一个法语名称.

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.

我想我必须先将这些特殊字符转换为html实体,然后再将其注入数据库,例如ö for ö.

And I thought I must convert these special characters into html entities before injecting them into database, like ö for ö.

如果我使用htmlspecialchars()进行转换,

 Array
(
    [name] => Löic
)

if(isset($_POST['name'])) $name = preg_replace('/\s\s+/', ' ', trim($_POST['name']));
$name = htmlspecialchars($name, ENT_QUOTES);

因此应将其转换为该Löic,而不是完全转换为原样,

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

如果我使用htmlentities()进行转换,

$name = htmlentities($name, ENT_QUOTES);

然后我明白了

Löic

,它在我的html上显示为

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?

与在该名称列中设置的utf8_general_ci有关吗?

Is it to do with utf8_general_ci which I set at that name column??

谢谢.

推荐答案

之所以会发生这种情况,是因为您尝试使用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.

这篇关于使用htmlspecialchars和htmlentities转换特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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