【问题标题】:Php text encodephp文本编码
【发布时间】:2015-01-25 18:08:12
【问题描述】:

我有一些代码会自动生成一个字符串,但一些特殊字符显示如下:�

代码:

header("Content-type: text/html; charset=utf-8");
function RandomString($length = 10){
    $chars ='0123456789abcdefghijklmnopqrstuvwxyzåäöABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ!#¤%&()=?@£$€{}[]+';
    $randString = '';
    for($i = 0; $i < $length; $i++){
        $randString .= $chars[rand(0, 88)];
    }
    echo $randString;
    return $randString;
}

【问题讨论】:

  • 你是在尝试“编码”“加密”还是“哈希”字符串..这三者之间有很大的不同。
  • @OrelEraki 你认为这个函数是如何加密或散列的?显然,这是一个关于字符编码的问题。
  • php 不知道您的字符串是带有 utf8 字符的字符串 - A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. - 请参阅 php.net/manual/en/language.types.string.php,尤其是字符串类型的详细信息。
  • 源文件的编码也必须是 UTF-8 才能使用此代码。您应该使用特殊的“Unicode”函数从字符串中提取第 i 个字符(因为某些字符需要两个或更多字节)。
  • @OrelEraki 该函数称为 RandomString。猜猜它的作用。

标签: php


【解决方案1】:

$chars 数组中有几个字符是多字节字符(准确地说是 UTF-8)。不幸的是,PHP 本身并不能很好地处理多字节字符。

这里的解决方案是将所有调用替换为支持多字节字符的变体。 mbstring 扩展提供了这样的支持。

您可以通过调用mb_substr 函数来替换$chars[rand(0,88)] 的调用。所以你会得到类似mb_substr($chars, rand(0, 88), 1)的东西。

【讨论】:

  • mb_substr($chars, rand(0,88),1,'utf8');完成了这项工作。
猜你喜欢
  • 2013-04-05
  • 1970-01-01
  • 1970-01-01
  • 2013-05-05
  • 2011-02-08
  • 2013-01-13
  • 1970-01-01
  • 1970-01-01
  • 2013-10-04
相关资源
最近更新 更多