如何在PHP中将UTF8字符转换为数字字符实体 [英] How to convert UTF8 characters to numeric character entities in PHP

查看:132
本文介绍了如何在PHP中将UTF8字符转换为数字字符实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PHP可以完全翻译下面的代码吗?

Is a translation of the below code at all possible using PHP?

下面的代码是用JavaScript编写的。它在需要时返回带有数字字符引用的html。例如 smslån-> smslå n

The code below is written in JavaScript. It returns html with numeric character references where needed. Ex. smslån -> smslån

我创建翻译失败。 此脚本看起来可能有效,但返回 & aring; 表示å ,而不是 å ,就像下面的JavaScript一样。

I have been unsuccessful at creating a translation. This script looked like it may work, but returns å for å instead of å as the javascript below does.

function toEntity() {
  var aa = document.form.utf.value;
  var bb = '';
  for(i=0; i<aa.length; i++)
  {
    if(aa.charCodeAt(i)>127)
    {
      bb += '&#' + aa.charCodeAt(i) + ';';
    }
    else
    {
      bb += aa.charAt(i);
    }
  }
  document.form.entity.value = bb;
}

PHP的ord函数听起来与 charCodeAt ,但不是。我使用ord获得 195 ,使用charCodeAt获得 229 。那,或者我遇到了一些难以置信的编码问题。

PHP's ord function sounds like it does the same thing as charCodeAt, but it does not. I get 195 for å using ord and 229 using charCodeAt. That, or I am having some incredibly difficult encoding problems.

推荐答案

使用 mb_encode_numericentity

$convmap = array(0x80, 0xffff, 0, 0xffff);
echo mb_encode_numericentity($utf8Str, $convmap, 'UTF-8');

这篇关于如何在PHP中将UTF8字符转换为数字字符实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆