doulan9419 2013-06-30 21:53
浏览 182
已采纳

str_replace不替换特殊字符

In a project of mine, I'm having a few upload forms. Since I live in Sweden, I want to encode the Swedish special characters to their respective HTML-code, so that encoding won't be an issue when displaying the data. Here's the code:

function format_text($text){
    $chars = ['å','ä','ö','Å','Ä','Ö'];
    $codes = ['å','ä','ö','&Aring','Ä','Ö'];
    foreach($chars as $key => $value){
        $text = str_replace($value,$codes[$key],$text);
    }
    $text = str_replace("","
",$text);
    $text = preg_replace("!

+!", "
", $text);
    $text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
    $lines = explode("
", $text);
    foreach ($lines as $key => $line){
        $lines[$key] = "<p>{$line}</p>";
    }
    $text = implode("
", $lines);
    return $text;
}

Anyway, after running this function I always get an empty string from the htmlspecialchars, which I've understood is because of the Swedish special chars which is never replaced. So, my question is this: Why isn't the special chars replaced with it's respective HTML-code, and how can I fix it? I'm using PHP5.4.

  • 写回答

1条回答 默认 最新

  • ds3016 2013-06-30 22:13
    关注

    If you used htmlentities instead of htmlspecialchars you wouldn't need str_replace:

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

    If that doesn't work, check that the text is encoded in UTF-8 and not something else.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?