Converting special characters with htmlspecialchars and htmlentities

笑着哭i 提交于 2020-01-04 05:38:26

问题


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.


回答1:


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.




回答2:


Also you can simple do:

$text = htmlspecialchars( $text );
$text = mysql_escape_string( $text );


来源:https://stackoverflow.com/questions/4786527/converting-special-characters-with-htmlspecialchars-and-htmlentities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!