When I replace é it changes into an é. I am using UTF-8 encoding in PHP and HTML. I want the function to return the HTML code for the character I put into the function.
function ctrlspecialchars($subject){
$search = array("<",">","é","à","â","ä","æ","ç","è","ê","ë","ï","î","ò","ó","ô","ö","ø","ù","ú","û","ü","©","®","«","»","¼","½","¾","±","§","¥","£","{","}","$","%");
$replace = array("<",">","é","à","â","ä","æ","ç","è","ê","ë","ï","î","ò","ó","ô","ö","ø","ù","ú","û","ü","©","®","«","»","¼","½","¾","±","§","¥","£","{","}","$","%");
return str_replace($search,$replace,$subject);
}
Try charset: iso-8859-1 instead of UTF-8 or be sure to set the charset in your html header:
PHP : header('Content-type: text/html; charset=utf-8');
HTML: <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
Since I copied your code and it works fine in my local environment, your problem shouldn't be in the code and should be indeed the encoding.
I don't know your encoding needs (maybe you need to print some special characters in some page), but for test purposes, try to keep all parts of your system to use UTF-8. Follow the tips of @user2879055's answer, configure your Database to use utf8_general_ci
and ensure that your PHP file is encoded in the UTF-8.
See below a image of my editor (I'm using Atom) configured to encoding the files in UTF-8. Most editors have a similar type of configuration. If your editor has two options of UTF-8 (with and without BOM), choose without BOM (informations here).
Finally, if your are using Apache, add the line IndexOptions +Charset=UTF-8
to your .htacces
.
Avoid the use of utf8_enconding
and utf8_decode
functions during these tests.
When it works, change back the enconding configuration for each step and make a test, so you'll find where is the problem when your code fails again. Now you can configure your enviroment with your enconding needs and work just on the problematic part.
Just FIY, I'm using your function with var_dump(ctrlspecialchars("<ó äî ò æ ç % ®>"));
and my browser is showing /var/www/html/replace.php:10:string '<ó äî ò æ ç % ®>' (length=61)
.