我有一个字符串,它看起来像"v''u00e4lkommen till mig",我在字符串上执行utf8_encode()后得到的。
我希望这个字符串变成
välkommen till mig
其中字符
'u00e4 = ä = ä
如何在PHP中实现这一点?
-
不要使用utf8_(de|en)代码。它只是从UTF8转换为ISO-8859-1并返回。ISO 8859-1没有提供与ISO-8859-15或Windows1252相同的字符,它们是最常用的编码(除了UTF-8)。最好使用mb_convert_encoding。
-
"v''u00e4lkommen till mig">此字符串看起来像一个JSON编码的字符串,它已经进行了utf8编码。"ä"的unicode代码位置是U+00E4>>''u00e4。
示例
<?php
header('Content-Type: text/html; charset=utf-8');
$json = '"v'u00e4lkommen till mig"';
var_dump(json_decode($json)); //It will return a utf8 encoded string "välkommen till mig"
这个字符串的来源是什么?
不需要将ä替换为其HTML表示形式ä,如果您将其打印在utf8编码的文档中,并告诉浏览器所使用的编码。如有必要,使用htmlentities
:
<?php
$json = '"v'u00e4lkommen till mig"';
$string = json_decode($json);
echo htmlentities($string, ENT_COMPAT, 'UTF-8');
编辑:由于您希望保留HTML字符,并且我现在认为您的源字符串与您发布的不完全一样(我认为它是实际的unicode,而不是包含'unnnn
作为字符串),我认为您最好的选择是:
$html = str_replace( str_replace( str_replace( htmlentities( $whatever ), '<', '<' ), '>', '>' ), '&', '&' );
(注意:没有呼叫utf8-decode
)
原始答案:
没有直接转换。首先,再次解码:
$decoded = utf8_decode( $whatever );
然后编码为HTML:
$html = htmlentities( $decoded );
当然,你可以在没有变量的情况下做到这一点:
$html = htmlentities( utf8_decode( $whatever ) );
http://php.net/manual/en/function.utf8-decode.php
http://php.net/manual/en/function.htmlentities.php
要通过正则表达式实现这一点(不推荐使用,可能较慢,可靠性较低),可以使用HTML支持&#xnnnn;
构造的事实,其中nnnn
与现有的'unnnn
值相同。所以你可以说:
$html = preg_replace( '/''''u([0-9a-f]{4})/i', '&#x$1;', $whatever )
html_entity_decode
对我有用。
$json = '"v'u00e4lkommen till mig"';
echo $decoded = html_entity_decode( json_decode($json) );