php 使用 HTML-ENTITIES 字符集替代 mb_convert_encoding

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11974008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:32:39  来源:igfitidea点击:

Alternative to mb_convert_encoding with HTML-ENTITIES charset

phpstringcharacter-encoding

提问by Simon

I have the following code:

我有以下代码:

mb_convert_encoding($string, 'HTML-ENTITIES', 'utf-8');

I need to have an alternative code which does exactly the same but does not use any mb_* functions (the mb extension is not available on some environments).

我需要一个完全相同的替代代码,但不使用任何 mb_* 函数(mb 扩展在某些环境中不可用)。

I thought that

我认为

utf8_decode(htmlentities($string, ENT_COMPAT, 'utf-8'));

should do exactly the same, but unfortunately it does not.

应该完全相同,但不幸的是它没有。

回答by Green Black

I played around a bit, and find this very interesting. It seems like the second part also runs "htmlspecialchars". Must be some bug in mb_convert_encoding, as htmlentities is not run correctly.

我玩了一会儿,发现这很有趣。似乎第二部分也运行“htmlspecialchars”。必须是 mb_convert_encoding 中的一些错误,因为 htmlentities 没有正确运行。

If you run htmlspecialchars_decode over the result, you get exactly the same as if you would use mb_convert_encoding.

如果您对结果运行 htmlspecialchars_decode,您将获得与使用 mb_convert_encoding 完全相同的结果。

The code:

编码:

$string = 'Test:!"$%&/()=??ü??ü<<';
echo mb_convert_encoding($string, 'HTML-ENTITIES', 'utf-8')."\n\n";
echo htmlspecialchars_decode(utf8_decode(htmlentities($string, ENT_COMPAT, 'utf-8', false)));

Here a demo of the code above: http://sandbox.onlinephpfunctions.com/code/715acade3b8337d9c9e48e58deee2a237015c259

这里是上面代码的演示:http: //sandbox.onlinephpfunctions.com/code/715acade3b8337d9c9e48e58deee2a237015c259

And here a demo without htmlspecialchars_decode, to show your problem: http://sandbox.onlinephpfunctions.com/code/5c4a32bf99aa8fd6246c4a77132a023d32945363

这里有一个没有 htmlspecialchars_decode 的演示,以显示您的问题:http: //sandbox.onlinephpfunctions.com/code/5c4a32bf99aa8fd6246c4a77132a023d32945363