php - 如何将 Unicode 特殊字符转换为 html 实体?

标签 php unicode utf-8 html-entities

我有以下字符串:

$string = "★ This is some text ★";

我想将它转换为 html 实体:

$string = "★ This is some text ★";

每个人都在写的解决方案:

htmlentities("★ This is some text ★", "UTF-8");

但是htmlentities不能把所有的unicode都转成html实体。所以它只给我与输入相同的输出:

★ This is some text ★

我还尝试将此解决方案与两者结合:

header('Content-Type: text/plain; charset=utf-8');

和:

mb_convert_encoding();

但这要么打印出空结果,要么根本不转换,要么错误地将星星转换为:

Â

如何将 ★ 和所有其他 unicode 字符转换为正确的 html 实体?

最佳答案

htmlentities 在这种情况下不起作用,但您可以尝试使用 UCS-4 对字符串进行编码,例如:

$string = "★ This is some text ★";
$entity = preg_replace_callback('/[\x{80}-\x{10FFFF}]/u', function ($m) {
    $char = current($m);
    $utf = iconv('UTF-8', 'UCS-4', $char);
    return sprintf("&#x%s;", ltrim(strtoupper(bin2hex($utf)), "0"));
}, $string);
echo $entity;

★ This is some text ★

Ideone Demo

关于php - 如何将 Unicode 特殊字符转换为 html 实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37183776/

相关文章:

python - 如何使用python从unicode转换

c++ - utf8 <-> utf16 : codecvt poor performance

python - SQL 数据库不接受 UTF -8 字符

php - 编译PHP 7时未找到Apache a2enmod,但这是必需的

javascript - 使用 getElementsByClassName 具有多个元素的 HTML Javascript setTimeout

php - 停止在 div 内的表中滚动表标题 <th>

perl - 使用带有 unicode 文件名的文件 I/O API 的通用方法是什么?

python - 如何以编程方式从十六进制中检索 unicode 字符?

ruby-on-rails - 将任何编码的字符串强制转换为 UTF-8

php - 分解数组以生成两个变量,以便我可以从数据库表中获取信息以发送电子邮件