Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: chr Function Issue with Special characters

Tags:

php

utf-8

chr

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.

like image 832
BisaZ Avatar asked Sep 26 '22 14:09

BisaZ


People also ask

How do you check if a string contains a special character in PHP?

php function check_string($my_string){ $regex = preg_match('[@_! #$%^&*()<>?/|}{~:]', $my_string); if($regex) print("String has been accepted"); else print("String has not been accepted"); } $my_string = 'This_is_$_sample!

Is CHR () and Ord () is opposite function in PHP?

To convert to ASCII from textual characters, you should use the chr() function, which takes an ASCII value as its only parameter and returns the text equivalent if there is one. The ord() function does the opposite - it takes a string and returns the equivalent ASCII value.

What does Chr do in PHP?

PHP chr() Function The chr() function returns a character from the specified ASCII value. The ASCII value can be specified in decimal, octal, or hex values. Octal values are defined by a leading 0, while hex values are defined by a leading 0x.


1 Answers

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

like image 86
Fabian Schmengler Avatar answered Oct 22 '22 21:10

Fabian Schmengler