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

hkmswyz6  于 2023-01-29  发布在  PHP
关注(0)|答案(2)|浏览(130)

我有以下字符串:

$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实体?

6mzjoqzu

6mzjoqzu1#

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

vs91vp4v

vs91vp4v2#

这样更好

html_entity_decode('zł');

输出-z

相关问题