7

How to convert all characters in a string to HTML entities?

htmlentities() doesn't work for characters like ćĆČ芚ĐđŽž

0

4 Answers 4

9
<?php

function encode($string) {
    return mb_encode_numericentity($string, array(0x000000, 0x10ffff, 0, 0xffffff), 'UTF-8');
}

echo encode('ćĆČ芚ĐđŽž');

Result is &#263;&#262;&#268;&#269;&#352;&#353;&#272;&#273;&#381;&#382;

Sign up to request clarification or add additional context in comments.

2 Comments

damn! after searching for hours, your answer saved me :)
This is great! Here’s another method FWIW stackoverflow.com/questions/42124369/…
2

There are no (named) entities for those characters.

You can see the list here. If you want to convert to numerical entities, see this answer.

2 Comments

Your recommended alternative function encode2() produces the following error: Parse error: syntax error, unexpected T_FUNCTION, expecting ')' on the line where the array_map is called
@A-OK It's written for PHP 5.3.
2

The character code of "ć", is 263, which as an HTML entity is &#263;, and so forth.

1 Comment

Convert first using htmlentities, then convert any characters which are outside the ASCII range in a second pass using preg_replace_callback and the regex "/[^\x00-\x7F]/".
2

It's widely known that some characters are not encoded with htmlentities();.

If you look at the docs, there are some posts with character maps you can use with str_replace()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.