str_replace不替换特殊字符


str_replace not replacing special chars

在我的一个项目中,我有一些上传表单。由于我住在瑞典,我想将瑞典的特殊字符编码到它们各自的HTML代码中,这样在显示数据时编码就不会成为问题。这是代码:

function format_text($text){
    $chars = ['å','ä','ö','Å','Ä','Ö'];
    $codes = ['å','ä','ö','&Aring','Ä','Ö'];
    foreach($chars as $key => $value){
        $text = str_replace($value,$codes[$key],$text);
    }
    $text = str_replace("'r","'n",$text);
    $text = preg_replace("!'n'n+!", "'n", $text);
    $text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
    $lines = explode("'n", $text);
    foreach ($lines as $key => $line){
        $lines[$key] = "<p>{$line}</p>";
    }
    $text = implode("'n", $lines);
    return $text;
}

无论如何,在运行这个函数后,我总是从htmlspecialchars中得到一个空字符串,我知道这是因为瑞典语的特殊字符永远不会被替换。所以,我的问题是:为什么不用它各自的HTML代码替换特殊字符,我该如何修复它?我用的是PHP5.4。

如果使用htmlentities而不是htmlspecialchars,则不需要str_replace:

$text = htmlentities($text, ENT_QUOTES, 'UTF-8');

如果这不起作用,请检查文本是否使用UTF-8编码,而不是其他格式。