str_replace 不替换特殊字符 [英] str_replace not replacing special chars

查看:35
本文介绍了str_replace 不替换特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
}

无论如何,在运行这个函数之后,我总是从 htmlspecialchars 得到一个空字符串,我明白这是因为瑞典的特殊字符永远不会被替换.所以,我的问题是:为什么不将特殊字符替换为其各自的 HTML 代码,我该如何解决?我使用的是 PHP5.4.

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.

推荐答案

如果你使用了 htmlentities 而不是 htmlspecialchars 你就不需要 str_replace:

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

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

如果这不起作用,请检查文本是否以 UTF-8 编码而不是其他编码.

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

这篇关于str_replace 不替换特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆