Convert special characters to HTML character codes

2019-02-13 21:17发布

I'm developing a CMS for a customer and he needs to edit stuff and use special characters such as ç and ®. 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?

5条回答
Viruses.
2楼-- · 2019-02-13 21:56

The easiest would be to use UTF-8 right from the start.
But you can also automatically convert characters with DOM:

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

outputs

© oui içi » 
查看更多
爷、活的狠高调
3楼-- · 2019-02-13 21:59

You can use htmlentities() to do that.

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

To turn entities back to readable text, use 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.

查看更多
放荡不羁爱自由
4楼-- · 2019-02-13 22:09

You can use:

htmlentities

查看更多
做个烂人
5楼-- · 2019-02-13 22:09

Take a look at the htmlentities function. This takes a string and converts component characters into their HTML entities. You can specify the encoding of the string to be consistent with the user's input.

查看更多
beautiful°
6楼-- · 2019-02-13 22:11

Use unicode, and show him how to copy&paste from character map :-)

查看更多
登录 后发表回答