【问题标题】:What encoding is this... and how do you escape it in php?这是什么编码......以及如何在 php 中转义它?
【发布时间】:2009-10-16 07:51:29
【问题描述】:
我正在为一个网站开发一个 imdb 数据抓取工具,我似乎用一种我以前从未见过的奇怪编码对所有内容进行编码。
<a href="/keyword/exploding-ship/">Exploding Ship</a>
A Bug's Life
有没有 php 函数可以将这些转换为常规字符?
【问题讨论】:
标签:
php
html
encoding
html-entities
【解决方案1】:
这不是编码,它是 html 实体的十六进制代码。
试试
$converted = html_entity_decode($string, ENT_QUOTES, 'UTF-8');
【解决方案2】:
这些是 SGML 字符转义。它们可以是十进制 (&#39;) 或十六进制 (&#xA0),并直接引用 Unicode 代码点。
html_entity_decode() 应该在 PHP 5 中工作。虽然我目前无法测试。
在该参考页面的第一条评论中,为旧 PHP 版本提供了以下代码:
// For users prior to PHP 4.3.0 you may do this:
function unhtmlentities($string)
{
// replace numeric entities
$string = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
$string = preg_replace('~&#([0-9]+);~e', 'chr("\\1")', $string);
// replace literal entities
$trans_tbl = get_html_translation_table(HTML_ENTITIES);
$trans_tbl = array_flip($trans_tbl);
return strtr($string, $trans_tbl);
}