Say I wanted to print a ÿ
(latin small y with diaeresis) from its Unicode/UTF-8 number of U+00FF
or hex of c3 bf
. How can I do that in PHP?
The reason is that I need to be able to create certain UTF-8 Characters is for testing in my regex and string functions. However, since I have less than 200 keys on my keyboard I开发者_如何学C can't type them - and since many times I am stuck in an ASCII only world - I need to be able to create them bases solely off of their ASCII safe, UTF-8 character code.
Note: In order for it show correctly in a browser I know that the first step is
header('Content-Type: text/html; charset=utf-8');
well you have everything you need.
Hex values being recognized in double-quoted strings as well
echo "\xc3\xbf";
Solution 1 with a small pack function
<?php
function chr_utf8($n,$f='C*'){
return $n<(1<<7)?chr($n):($n<1<<11?pack($f,192|$n>>6,1<<7|191&$n):
($n<(1<<16)?pack($f,224|$n>>12,1<<7|63&$n>>6,1<<7|63&$n):
($n<(1<<20|1<<16)?pack($f,240|$n>>18,1<<7|63&$n>>12,1<<7|63&$n>>6,1<<7|63&$n):'')));
}
echo chr_utf8(9405).chr_utf8(9402).chr_utf8(9409).chr_utf8(9409).chr_utf8(9412);
//Output ⒽⒺⓁⓁⓄ
Check it in https://eval.in/748062 …
Solution 2 with json_decode
<?php
$utf8_char='["';
for($number=0;$number<55296;$number++)
$utf8_char.='\u'.substr('000'.strtoupper(dechex($number)),-4).'","';
$utf8_char=json_decode(substr($utf8_char,0,-2).']');
echo $utf8_char[9405].$utf8_char[9402].$utf8_char[9409].$utf8_char[9409].$utf8_char[9412];
//Output ⒽⒺⓁⓁⓄ
精彩评论