PHP: chr Function Issue with Special characters
Asked Answered
W

1

6

In PHP i have the following code:

<?php
  echo "€<br>";
  echo ord("€") . "<br>";
  echo chr(128) . "<br>";

And i get the following output:

€
128
�

Why can't the chr function provide me the € sign? How can i get the €? I really need this to work. Thank's in advance.

Wristwatch answered 30/9, 2015 at 11:31 Comment(6)
I need the actual € sign inside a string.Wristwatch
what is the file saved as, UTF-8 (with/without BOM)? could be the issue. Save it as ANSI and all 3 echos will appear correctly.Adamec
It's saved as an UTF-8 without BOM.Wristwatch
When using UTF-8, ord('€') returns 226 instead of 128 (the latter is the Latin 1 decimal code)Thorman
I was getting 226 rather than 128 for the second one, so something doesn't pan out here, when saved as UTF-8 (with/without BOM).Adamec
Ok created a new file and converted with notepad++ and it gives me 226.Wristwatch
C
5

chr and ord only work with single byte ASCII characters. More specifically ord only looks at the first byte of its parameter.

The Euro sign is a three byte character in UTF-8: 0xE2 0x82 0xAC, so ord("€") (with the UTF-8 symbol) returns 226 (0xE2)

For characters that are also present in the ISO-8859-1 (latin1) character set, you can use utf8_encode() and utf8_decode(), but unfortunately the € sign is not contained there, so utf8_decode('€') will return "?" and cannot be converted back.

TL;DR: You cannot use ord and chr with a multi-byte encoding like UTF-8

Chasechaser answered 30/9, 2015 at 11:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.