简体   繁体   English

将特殊字符转换为HTML字符代码

[英]Convert special characters to HTML character codes

I'm developing a CMS for a customer and he needs to edit stuff and use special characters such as ç and ® . 我正在为客户开发CMS,他需要编辑内容并使用特殊字符,例如ç® However, I don't want him to have to enter the character codes like ® 但是,我不希望他输入像®这样的字符代码® . Does anyone knows a good way to automatically convert those characters using PHP? 有谁知道使用PHP自动转换这些字符的好方法?

You can use htmlentities() to do that. 你可以使用htmlentities()来做到这一点。

php -r 'echo htmlentities("®ç", ENT_COMPAT, "UTF-8"), "\n";'
®ç

To turn entities back to readable text, use html_entity_decode(): 要将实体转回可读文本,请使用html_entity_decode():

php -r 'echo html_entity_decode("®ç", ENT_COMPAT, "UTF-8"), "\n";'
®ç

If you're not using unicode, omit the charset name or give the correct charset. 如果您不使用unicode,请省略charset名称或提供正确的charset。

The easiest would be to use UTF-8 right from the start. 最简单的方法是从一开始就使用UTF-8。
But you can also automatically convert characters with DOM: 但您也可以使用DOM自动转换字符:

$dom = new DOMDocument;
$dom->appendChild(new DOMText('© oui içi » '));
echo $dom->saveHtml();

outputs 输出

© oui içi » 

使用unicode,并告诉他如何从字符映射中复制和粘贴:-)

You can use: 您可以使用:

htmlentities ヶ辆

Take a look at the htmlentities function. 看看htmlentities函数。 This takes a string and converts component characters into their HTML entities. 这将获取一个字符串并将组件字符转换为其HTML实体。 You can specify the encoding of the string to be consistent with the user's input. 您可以指定字符串的编码以与用户的输入一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM