问题
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