【问题标题】:Get hexcode of html entities获取 html 实体的十六进制代码
【发布时间】:2011-11-20 22:19:51
【问题描述】:

我有一个字符串为“€”。

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

所有货币符号都相同..

 £  ->  \u00A3
 $ ->  \u0024
 etc

【问题讨论】:

    标签: php flash unicode hex


    【解决方案1】:

    首先,请注意$ 不是known entity in HTML 4.01。但是,在 HTML 5 中,在 PHP 5.4 中,您可以调用 html_entity_decodeENT_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

    【讨论】:

    • 我的 php 版本是 5.1.6...它在 mb_convert_encoding 处显示致命错误...请问我怎样才能获得该值....
    • @PRA 如果您愿意,可以使用 iconv 代替 mbstring。如果您也没有 iconv,则必须手动将 UTF-8 转换为 UTF-16。
    • 我试过 iconv() 但我无法识别字符集类型来转换十六进制
    【解决方案2】:

    您可以尝试以下函数将字符串转换为十六进制:

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

    来自Greg Winiarski,即fourth hit on Google

    结合html_entity_decode()。所以是这样的:

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

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

    【讨论】:

    • -1 仅适用于代码点
    • 顺便说一句,在 PHP 5.4 中,当 html_entity_decode 的默认值变为 UTF-8 而不是 ISO-8859-1 时,它会失败得更厉害。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    • 2014-11-22
    • 2012-10-13
    • 2011-03-29
    • 2014-10-25
    • 1970-01-01
    • 2012-10-28
    相关资源
    最近更新 更多