gpt4 book ai didi

php - php 可以检测 4 字节编码的 utf8 字符吗?

转载 作者:IT王子 更新时间:2023-10-29 00:07:06 27 4
gpt4 key购买 nike

我在 mysql 5.1 服务器中使用 utf8 字符集 mysql 表,它不支持表中的 utf8mb4 编码。插入 4 字节编码的 utf8 字符时,如 "𡃁","𨋢","𠵱","𥄫","𠽌","唧","𠱁"。该表将弹出错误或跳过以下文本。

如何以编程方式在 PHP 中检测 4 字节编码的 utf8 字符并替换它们?

最佳答案

以下正则表达式将替换 4 字节 UTF-8 字符:

function replace4byte($string, $replacement = '') {
return preg_replace('%(?:
\xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)%xs', $replacement, $string);
}

var_dump(replace4byte('d'), replace4byte('d𡃁d'));

这不依赖于 /u 修饰符,因此您不必担心 UTF-8 编译 PCRE。但是,如果您有这种支持,deceze 的 preg_replace_callback 更整洁。

(正则表达式改编自Ensuring valid utf-8 in PHP)

关于php - php 可以检测 4 字节编码的 utf8 字符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16496554/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com