str_replace not replacing special chars

流过昼夜 提交于 2019-12-11 02:46:35

问题


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("\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;
}

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:


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.



来源:https://stackoverflow.com/questions/17395212/str-replace-not-replacing-special-chars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!