我有一个字符串“€
”。
我想将它转换为十六进制以获得 "\u20AC"
的值,以便我可以将它发送到闪存。
所有货币符号都一样..
£ -> \u00A3
$ -> \u0024
etc
最佳答案
首先,请注意 $
不是 known entity in HTML 4.01 .但是,在 HTML 5 中,在 PHP 5.4 中,您可以使用 ENT_QUOTES | 调用
对其进行解码。html_entity_decode
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("€foobar ´");
给出:
\u20ACfoobar \u00B4
关于php - 获取 html 实体的十六进制代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7482977/