Yur*_*riy 13 php decode html-entities
我正在尝试将编码的长短划线从数字实体解码为字符串,但似乎我找不到能够正确执行此操作的函数.
我找到的最好的是mb_decode_numericentity(),但由于某种原因,它无法解码长划线和其他一些特殊字符.
$str = '–';
$str = mb_decode_numericentity($str, array(0xFF, 0x2FFFF, 0, 0xFFFF), 'ISO-8859-1');
Run Code Online (Sandbox Code Playgroud)
这将返回"?".
谁知道如何解决这个问题?
Pek*_*ica 19
以下代码片段(大部分从此处被盗并经过改进)将适用于文字,数字十进制和数字十六进制实体:
header("content-type: text/html; charset=utf-8");
/**
* Decodes all HTML entities, including numeric and hexadecimal ones.
*
* @param mixed $string
* @return string decoded HTML
*/
function html_entity_decode_numeric($string, $quote_style = ENT_COMPAT, $charset = "utf-8")
{
$string = html_entity_decode($string, $quote_style, $charset);
$string = preg_replace_callback('~&#x([0-9a-fA-F]+);~i', "chr_utf8_callback", $string);
$string = preg_replace('~&#([0-9]+);~e', 'chr_utf8("\\1")', $string);
return $string;
}
/**
* Callback helper
*/
function chr_utf8_callback($matches)
{
return chr_utf8(hexdec($matches[1]));
}
/**
* Multi-byte chr(): Will turn a numeric argument into a UTF-8 string.
*
* @param mixed $num
* @return string
*/
function chr_utf8($num)
{
if ($num < 128) return chr($num);
if ($num < 2048) return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
if ($num < 65536) return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
if ($num < 2097152) return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
return '';
}
$string ="”";
echo html_entity_decode_numeric($string);
Run Code Online (Sandbox Code Playgroud)
欢迎改进建议.
mb_decode_numericentity不处理十六进制,只处理十进制。您是否得到了预期的结果:
$str = '\xe2\x80\x93';\n\n$str = mb_decode_numericentity ( $str , Array(255, 3145727, 0, 65535) , 'ISO-8859-1');\nRun Code Online (Sandbox Code Playgroud)\n\n您可以使用hexdec将十六进制转换为十进制。
另外,出于好奇,做了以下工作:
\n\n$str = '–';\n\n $str = html_entity_decode($str);\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
6960 次 |
| 最近记录: |