获取html实体的十六进制代码

时间:2011-09-20 09:29:35

标签: php flash unicode hex

我的字符串为“€”。

我想将其转换为十六进制以获取值"\u20AC",以便我可以将其发送到闪存。

所有货币符号相同..

 £  ->  \u00A3
 $ ->  \u0024
 etc

2 个答案:

答案 0 :(得分:3)

首先,请注意$不是known entity in HTML 4.01。但是,它是在HTML 5中,并且在PHP 5.4中,您可以使用html_entity_decode调用ENT_QUOTES | ENT_HTML5来解码它。

您必须解码实体,然后才转换它:

//assumes $str is in UTF-8 (or ASCII)
function foo($str) {
    $dec = html_entity_decode($str, ENT_QUOTES, "UTF-8");
    //convert to UTF-16BE
    $enc = mb_convert_encoding($dec, "UTF-16BE", "UTF-8");
    $out = "";
    foreach (str_split($enc, 2) as $f) {
        $out .= "\\u" . sprintf("%04X", ord($f[0]) << 8 | ord($f[1]));
    }
    return $out;
}

如果您只想替换实体,可以使用preg_replace_callback来匹配实体,然后使用foo作为回调。

function repl_only_ent($str) {
    return preg_replace_callback('/&[^;]+;/',
        function($m) { return foo($m[0]); },
    $str);
}

echo repl_only_ent("&euro;foobar &acute;");

给出:

\u20ACfoobar \u00B4

答案 1 :(得分:-1)

您可以尝试使用以下函数进行字符串到十六进制转换:

function strToHex($string) {
    $hex='';
    for ($i=0; $i < strlen($string); $i++) {
        $hex .= dechex(ord($string[$i]));
    }
    return $hex;
}

来自Greg Winiarskifourth hit on Google

html_entity_decode()结合使用。所以像这样:

$currency_symbol = "&euro;";
$hex = strToHex(html_entity_decode($currency_symbol));

此代码未经测试,因此可能需要进一步修改才能返回您需要的确切结果