Skip to content
Advertisement

convert decimal value to unicode characters in php

i need to convert decimals values into unicode and display the unicode character in PHP.

so for example, 602 will display as this character: ɚ

after referencing this SO question/answer, i was able to piece this together:

echo  json_decode('"' . 'u0' . dechex(602) . '"' );

this seems pretty error-prone. is there a better way to do this?

i was unable to get utf8_encode to work since it seemed to want to start with a string, not a decimal.

EDIT: in order to do characters between 230 and 250, double prefixed zeros are required:

 echo   json_decode('"' . 'u00' . dechex(240) . '"' );  // ð
 echo   json_decode('"' . 'u00' . dechex(248) . '"' );  // ø
 echo   json_decode('"' . 'u00' . dechex(230) . '"' );  // æ

in some cases, no zero is required:

echo json_decode('"' . 'u' . dechex(8592) . '"' );  // ←

this seems strange.

Advertisement

Answer

While eval is generally to be avoided, it seems strictly-controlled enough to be fine here.

echo eval(sprintf('return "u{%x}";',$val));
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement