【问题标题】:How to correctly encode ascii text with php?如何使用 php 正确编码 ascii 文本?
【发布时间】:2014-02-06 10:30:27
【问题描述】:

好的 - 我使用 file_get_contents() 来接收 txt 文件的内容。我检查了这一行:$encoding=mb_detect_encoding($texts, 'auto'); 它是哪种编码,输出是 ascii。

通常 ascii 在某种程度上是 utf-8,但我得到的不是长破折号,而是这个有趣的符号:

——

使用$texts=iconv('ASCII', 'UTF-8//IGNORE', $texts);,我能够删除这些符号,但我想保留它们。

我也尝试用普通破折号替换它们:

$texts=str_replace('–', '-', $texts);

但这没有用。也许还有其他奇怪的符号 - 我怎样才能正确编码它们或用类似的符号替换它们?

【问题讨论】:

    标签: php encoding utf-8 char


    【解决方案1】:

    这个有用的forceutf8 库可以处理和纠正混合编码的字符串:

    PHP 类编码具有流行的 Encoding::toUTF8() 函数 -- 以前称为 forceUTF8()-- 修复混合编码字符串。

    【讨论】:

    • 谢谢!但是出现以下错误:“致命错误:在...中找不到类'编码'”这不是标准的PHP函数,对吧?
    • 我从 github.com/neitanod/forceutf8 下载了 Encoding.php 并在我的脚本中使用了 require_once() 来导入它。然后发生以下错误:“致命错误:命名空间声明语句必须是脚本中的第一个语句” - 所以我取消了它的注释(//namespace ForceUTF8;)。然后我使用了 Encoding::toUTF8() 函数但没有任何改变:(
    • 我不明白。我导入 Encoding.php 并没有取消注释命名空间行并收到错误“致命错误:在...中找不到类'编码'”但路径正确且文件正确且我在主 php 中的代码行是 $text_content=file_get_contents(Encoding::toUTF8($text));所以通常它应该工作。我做错了什么?
    【解决方案2】:

    终于在this site的这个函数中找到了答案。

    我尝试了很多不同的方法,但最终这是唯一有效的方法。

    【讨论】:

    • 上述来自 Alan Whipple 的函数如下:
    【解决方案3】:

    user2718671 引用的功能(由 Alan Whipple 提供)在网站消失的情况下引用如下:

        function cleanEncoding( $text, $type='standard' ){
        // determine the encoding before we touch it
        $encoding = mb_detect_encoding($text, 'UTF-8, ISO-8859-1');
        // The characters to output
        if ( $type=='standard' ){
            $outp_chr = array('...',          "'",            "'",            '"',            '"',            'â¢',            '-',            '-'); // run of the mill standard characters
        } elseif ( $type=='reference' ) {
            $outp_chr = array('…',      '‘',      '’',      '“',      '”',      '•',      '–',      '—'); // decimal numerical character references
        }
        // The characters to replace (purposely indented for comparison)
            $utf8_chr = array("\xe2\x80\xa6", "\xe2\x80\x98", "\xe2\x80\x99", "\xe2\x80\x9c", "\xe2\x80\x9d", '\xe2\x80\xa2', "\xe2\x80\x93", "\xe2\x80\x94"); // UTF-8 hex characters
            $winc_chr = array(chr(133),       chr(145),       chr(146),       chr(147),       chr(148),       chr(149),       chr(150),       chr(151)); // ASCII characters (found in Windows-1252)
        // First, replace UTF-8 characters.
        $text = str_replace( $utf8_chr, $outp_chr, $text);
        // Next, replace Windows-1252 characters.
        $text = str_replace( $winc_chr, $outp_chr, $text);
        // even if the string seems to be UTF-8, we can't trust it, so convert it to UTF-8 anyway
        $text = mb_convert_encoding($text, 'UTF-8', $encoding);
        return $text;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多