如何在 php 中将 ascii 字母表更改为 utf-8

how to change ascii alphabet to utf-8 in php

我有一个 ASCII 字符串。我喜欢将其编码更改为 utf-8。 但是我发现在 php 中有一个简单的函数可以将 ascii 更改为 utf-8。 反之亦然,我喜欢将 utf-8 字母表更改为 ascii。 请指教

我试过:

<?php
// utf-8
$str = "CHONKIOK";  
// I can't even how to print these utf-8 characters in php. I just copied/pasted the string. 
// strlen($str) => 24 bytes
// mb_detect_encoding($str) => utf-8

$str2 = "CHONKIOK";
// strlen($str2) => 8 bytes
// mb_detect_encoding($str2) => ascii

// change ascii to utf-8
$str = mb_convert_encoding($str2, "UTF-8");

echo mb_detect_encoding($str);
// returns ascii

你的做法是正确的。 根据 mb_detect_encoding,它声明它检测到 最有可能 字符编码。

由于整个 ASCII 集包含在 UTF-8 中完全相同的字符位置,因此此函数告诉您它是一个 ASCII 字符串,因为它在技术上是。当以 ASCII 和 UFT-8 编码时,此字符串的字节是相同的。

如您所见,当您在 ASCII 集之外包含一些字符时,它将为您提供下一个可能的编码。

我应该怎么做才能从“CHONKIOK”中得到这个字符串:“CHONKOOK”?

您搜索的字符称为“全角拉丁语”字符。

鉴于提供的 字符是字符 65,315 而常规 C 是字符 67,您可以通过添加 65,248 的差异来获得您想要的字符串。这是唯一可能的,因为字母表往往在字符图表的不同部分以相同的顺序重复。

在加上65,248后mb_ord and convert it back to a character using mb_chr可以得到一个字符的code point

这可能看起来像:

$str_input = "ABC abc 123";
$convertable = "ABCDEFG12349abcdefg";
$str_output = "";

for ($i = 0; $i < strlen($str_input); $i++) {
    $char = mb_ord($str_input[$i], "UTF-8");
    if(str_contains($convertable, $str_input[$i])) $char += 65248;
    $str_output .= mb_chr($char, "UTF-8");
}

echo $str_output;  // outputs "ABC abc 123"

请务必将整个字母表包含在 $convertable

尝试将其转换为 utf-8:

utf8_encode(string $string): string

尝试将其转换为 ASCII:

utf8_decode(string $string): string