在PHP中解码没有分号的HTML实体

时间:2014-04-21 09:25:27

标签: php html character html-entities

HTML的现代方言和良好做法规则不允许在HTML实体中省略分号(&likethat;)。但是我有一个任务来解析任意页面,并且必须处理不带分号的坏html实体。这完全由浏览器呈现。如何使用PHP将没有分号的HTML实体解码为各自的UTF-8等价物?

2 个答案:

答案 0 :(得分:1)

您可以获取所有html实体的列表,并使用它来替换所有没有分号的UTF-8表示:

// get all HTML entities
$mapping = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | ENT_HTML5, 'UTF-8');

// change array values representing the entities to regex pattern with negativ lookahead for semicolon
array_walk($mapping, function(&$value) { $value = '/'.rtrim($value, ';').'(?!;)/'; });

// replace all entities without semicolon by their utf8 representation
$html = preg_replace(array_values($mapping), array_keys($mapping), $html);

答案 1 :(得分:0)

我的猜测是您可以尝试使用DOMDocument::loadHTML加载文档,然后尝试保存,然后使用DOMDocument::saveHTML

您可以使用libxml constants指定其他选项。

相关问题