我有一堆我正在处理的文本/ html文档
其中一些包含编码的html实体,我试图将其转换为原始解码的utf字符.
这很容易使用html_entity_decode,但是,有些实体是无效的,例如
򙦙
出于这个原因,我正在使用正则表达式来提取每个单独的实体,然后尝试以某种方式验证它们.
如果实体无效,我想将其保留为򙦙在文档中,但像编码和放大器的东西;仍然会成为& ;.
只是一些示例测试代码我敲了..
<?PHP function dump_chars($s) { if (preg_match_all('/&[#A-Za-z0-9]+;/',$s,$matches)) { foreach ($matches[0] as $m) { $decoded = html_entity_decode($m,ENT_QUOTES,"UTF-8"); echo "[" . htmlentities($m,"UTF-8") . "] "; echo "Decoded: [" . $decoded . "] "; echo "Hex: [" . bin2hex($decoded) . "] "; echo "detect: [" . mb_detect_encoding($decoded) . "]"; echo "<br>"; } } } $payload = "" & ͉ ’ 򙦙"; echo "<html><head><Meta charset='UTF-8'></head><body>"; dump_chars($payload);
我对如何最好地验证实体有点空白,请帮忙.
@H_403_17@@H_403_17@
我终于找到了办法……
function decode_numeric_entities($s) { $result = $s; $convmap = array(0x0,0x2FFFF,0xFFFF); if (preg_match_all('/&[#A-Za-z0-9]+;/',$matches)) { foreach ($matches[0] as $m) { $decoded = mb_decode_numericentity($m,$convmap,'UTF-8'); $result = str_replace($m,$decoded,$result); } } return $result; }
通过此func运行字符串会将所有有效实体转换为其实际的utf字符,并将所有无效实体保留为实体
@H_403_17@ 原文链接:https://www.f2er.com/php/136364.html