转换HTML实体在UTF-8到SHIFT_JIS


Converting HTML Entities in UTF-8 to SHIFT_JIS

我正在与一个网站,需要针对旧的,日本手机,这不是Unicode启用。问题是,网站的文本以HTML实体(即Ӓ)的形式保存在数据库中。这个数据库绝对不能更改,因为它被几百个网站使用。

我需要做的是将这些实体转换为实际字符,然后在发送之前转换字符串编码,因为手机渲染实体而不首先转换它们。

我已经尝试了mb_convert_encodingiconv,但他们所做的只是转换实体的编码,而不是创建文本。

Thanks in advance

编辑:

我也试过html_entity_decode。它产生相同的结果——一个未转换的字符串。

这是我正在使用的样本数据。

期望结果:&

HTML代码:シェラトン・ヌーサリゾート&スパ

html_entity_decode([the string above],ENT_COMPAT,'SHIFT_JIS');的输出与输入字符串相同

只要注意从实体中创建正确的代码点即可。如果原始编码为UTF-8,例如:

$originalEncoding = 'UTF-8'; // that's only assumed, you have not shared the info so far
$targetEncoding = 'SHIFT_JIS';
$string = '... whatever you have ... ';
// superfluous, but to get the picture:
$string = mb_convert_encoding($string, 'UTF-8', $originalEncoding);
$string = html_entity_decode($string, ENT_COMPAT, 'UTF-8');
$stringTarget = mb_convert_encoding($string, $targetEncoding, 'UTF-8');

我在php.net上发现了这个函数,它适用于我的例子:

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);
}

我认为你只需要html_entity_decode

编辑:基于您的编辑:

$output = preg_replace_callback("/(&#[0-9]+;)/", create_function('$m', 'return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); '), $original_string); 

注意,这只是将实体转换为实际字符的第一步。

只是为了参与,因为我在编码时遇到了某种编码错误,我建议使用以下代码段:

 $string_to_encode=" your string ";
 if(mb_detect_encoding($string_to_encode)!==FALSE){
      $converted_string=mb_convert_encoding($string_to_encode,'UTF-8');
 }

对于大量数据来说可能不是最好的,但仍然可以工作。