Search code examples
phphtmlregexcontent-management-systemspecial-characters

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 ®. 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?


Solution

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