dsjojts9734 2016-05-12 10:10
浏览 496
已采纳

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

I have the following string:

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

I want to convert it to html entities:

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

The solution everyone is writing about:

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

But htmlentities can't convert all unicodes to html entities. So it just gives me the same output as the input:

★ This is some text ★

I've also tried to combine this solution with both:

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

and:

mb_convert_encoding();

But this either prints and empty result, doesn't convert at all or wrongly converts the stars to:

Â

How to I convert ★ and all other unicode characters to the correct html entity?

  • 写回答

1条回答 默认 最新

  • dongluanan7163 2016-05-12 10:33
    关注

    htmlentities won't work in this case, but you can try to UCS-4 encode the string, something like :

    $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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮