2011-09-20 98 views
3

我有一個字符串爲「€」。獲取html實體的十六進制代碼

我想將其轉換爲十六進制以獲得值爲"\u20AC",以便我可以將它發送到閃存。

同樣爲所有貨幣符號..

£ -> \u00A3 
$ -> \u0024 
etc 

回答

3

首先,請注意$不是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
+0

我的PHP版本是5.1.6 ...它在mb_convert_encoding顯示致命錯誤...我怎麼能得到值... – Priya

+0

@PRADEEP見http://php.net/manual/en/mbstring.installation .php – Treffynnon

+0

@PRA如果您願意,您可以使用iconv而不是mbstring。如果您還沒有iconv,則必須手動將UTF-8轉換爲UTF-16。 – Artefacto

-1

你可以嘗試爲字符串下面的函數來進制轉換:

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)); 

此代碼是未經測試,因此可能需要進一步修改,返回確切的結果,你需要

+0

-1僅與代碼點工作原理<= U + 00FF(失敗,€,例如)和甚至然後它不添加\ U00。另外,要將字符串轉換爲十六進制,則有bin2hex,不需要您的功能。 – Artefacto

+0

順便說一句,在PHP 5.4中,當html_entity_decode的默認值變成UTF-8而不是ISO-8859-1時,它將失敗得更加壯觀。 – Artefacto