Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP function chr and ord with special chars

In PHP when I use the ord function in order to catch the ASCII code of my character I get this behavior:

ord("a") // return 97
chr(97) // return a

But when I use a special character like Œ the returns are different:

ord("Œ") // return 197
chr(197) // return �

All of my pages are encoded in utf8. This behaviour is the same for most of the special characters.

Has somebody seen this problem in the past? How can I fix it?

like image 897
Thibault KEROUANTON Avatar asked Dec 28 '25 02:12

Thibault KEROUANTON


1 Answers

ord() and chr() both use the ASCII values of characters, which is a single byte encoding. Œ is not a valid character in ASCII.

You can get each byte of a multi-byte character by specifying the byte offset, as follows:

$oethel = "Œ";
$firstByte = ord($oethel[0]); // 197
$secondByte = ord($oethel[1]); // 146

Reversing the process, however, does not work, because assigning to a string byte offset converts that string to an array:

$newOethel = "";
$newOethel[0] = chr(197);
$newOethel[1] = chr(146);
echo $newOethel;
// Output is as follows: 
// PHP Notice:  Array to string conversion
// Array
like image 81
Ghedipunk Avatar answered Dec 30 '25 17:12

Ghedipunk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!