简体   繁体   中英

Saving special characters in php

I've been reading for hours and I can't wrap my head completely around the encoding problem. I am using PHP Specifying charset=utf-8. I want to be able to input certain characters eg the bullet • and the arrow ⇒ into a textarea. I save directly to an mySQL Database and the symbols are correctly stored there. To display the saved text from the database, I call the following function to translate the stored symbols for the textarea.

function htmlspecialchars2($string, $flags=ENT_NOQUOTES){
$string = htmlspecialchars($string, $flags);    // to help prevent code injection
$string = str_replace(chr(149), "&#8226", $string);  // converts bullet to html
$string = str_replace("⇒", "&#8658",$string);   // don't know the ascii code for the arrow
return $string;
}

This works for the bullet but not for the arrow. Any suggestions how to save (and then re-display) extended HTML characters. I've read everything I can find, but am missing something.

You're probably looking for htmlentities . That should convert all characters that have HTML character entity equivalents into HTML entities (to reverse that use html_entity_decode ).


PS: on my system, htmlentities('⇒', ENT_COMPAT, 'UTF-8') returns ⇒

For anyone that follows, the solution had 2 parts

1) htmlentities was needed as mentioned by One Trick Pony (thank you!) and that was the real answer.

2) However, the other half was needing to explicitly set the encoding for the session. mysqli_set_charset($link, "utf8");

Note: the new code is much simpler. Instead of calling a special function htmlspecialchars2() as shown above, I can simply call htmlentities($string, ENT_NOQUOTES, 'UTF-8')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM