Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

php - Alternative to mb_convert_encoding with HTML-ENTITIES charset

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).

I thought that

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

The code:

$string = 'Test:!"$%&/()=??ü??ü<<';
echo mb_convert_encoding($string, 'HTML-ENTITIES', 'utf-8')."

";
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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...