PHP特殊字符替换函数

时间:2016-10-31 10:56:45

标签: php function replace str-replace

当我更换é时,它变成了é。我在PHP和HTML中使用UTF-8编码。我希望函数返回我放入函数的字符的HTML代码。

function ctrlspecialchars($subject){    
$search = array("<",">","é","à","â","ä","æ","ç","è","ê","ë","ï","î","ò","ó","ô","ö","ø","ù","ú","û","ü","©","®","«","»","¼","½","¾","±","§","¥","£","{","}","$","%");
$replace = array("&lt;","&gt;","&#233;","&#224;","&#226;","&#228;","&#230;","&#231;","&#232;","&#234;","&#235;","&#239;","&#238;","&#242;","&#243;","&#244;","&#246;","&#248;","&#249;","&#250;","&#251;","&#252;","&#169;","&#174;","&#171;","&#187;","&#188;","&#189;","&#190;","&#177;","&#167;","&#165;","&#163;","&#123;","&#125;","&#36;","&#37;");

return str_replace($search,$replace,$subject); 
 }

2 个答案:

答案 0 :(得分:0)

尝试charset:iso-8859-1而不是UTF-8或确保在html标头中设置charset:

PHP : header('Content-type: text/html; charset=utf-8');
HTML: <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

答案 1 :(得分:0)

由于我复制了你的代码并且它在我的本地环境中工作正常,你的问题不应该在代码中,而应该是编码。

我不知道您的编码需求(可能需要在某些页面中打印一些特殊字符),但出于测试目的,请尽量保持系统的所有部分都使用UTF-8。 按照@ user2879055的答案提示,配置数据库以使用utf8_general_ci并确保您的PHP文件以UTF-8编码。

请参阅下面我的编辑器(我正在使用Atom)配置为以UTF-8编码文件的图像。大多数编辑器都有类似的配置。如果您的编辑器有两个UTF-8选项(有和没有BOM),请选择不带BOM(信息here)。

atom configuration

最后,如果您使用的是Apache,请将行IndexOptions +Charset=UTF-8添加到.htacces

在这些测试中避免使用utf8_encondingutf8_decode函数。

当它工作时,更改每个步骤的enconding配置并进行测试,这样当代码再次失败时,您将找到问题所在。现在,您可以根据您的需求配置您的环境,并仅针对有问题的部分开展工作。

只是FIY,我在var_dump(ctrlspecialchars("<ó äî ò æ ç % ®>"));使用您的功能,我的浏览器显示/var/www/html/replace.php:10:string '&lt;&#243; &#228;&#238; &#242; &#230; &#231; &#37; &#174;&gt;' (length=61)