From 2901d27235c9406da285a7c50ad5a9499c50f32e Mon Sep 17 00:00:00 2001 From: Progi1984 Date: Wed, 1 Jul 2015 16:13:48 +0200 Subject: [PATCH] Added String::chr for suppporting Unicode Characters --- src/Common/String.php | 22 ++++++++++++++++++++++ tests/Common/Tests/StringTest.php | 13 +++++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/Common/String.php b/src/Common/String.php index 598db4b..aa7b03e 100644 --- a/src/Common/String.php +++ b/src/Common/String.php @@ -74,4 +74,26 @@ public static function numberFormat($number, $decimals) { return number_format($number, $decimals, '.', ''); } + + /** + * @param int $dec + * @link http://stackoverflow.com/a/7153133/2235790 + * @author velcrow + */ + public static function chr($dec) + { + if ($dec<=0x7F) { + return chr($dec); + } + if ($dec<=0x7FF) { + return chr(($dec>>6)+192).chr(($dec&63)+128); + } + if ($dec<=0xFFFF) { + return chr(($dec>>12)+224).chr((($dec>>6)&63)+128).chr(($dec&63)+128); + } + if ($dec<=0x1FFFFF) { + return chr(($dec>>18)+240).chr((($dec>>12)&63)+128).chr((($dec>>6)&63)+128).chr(($dec&63)+128); + } + return ''; + } } diff --git a/tests/Common/Tests/StringTest.php b/tests/Common/Tests/StringTest.php index 5e2d24b..fcad14d 100644 --- a/tests/Common/Tests/StringTest.php +++ b/tests/Common/Tests/StringTest.php @@ -43,4 +43,17 @@ public function testNumberFormat() $this->assertEquals('2.1', String::numberFormat('2.12', 1)); $this->assertEquals('1234', String::numberFormat(1234, 1)); } + + public function testChr() + { + $this->assertEquals('A', String::chr(65)); + $this->assertEquals('A', String::chr(0x41)); + $this->assertEquals('é', String::chr(233)); + $this->assertEquals('é', String::chr(0xE9)); + $this->assertEquals('⼳', String::chr(12083)); + $this->assertEquals('⼳', String::chr(0x2F33)); + $this->assertEquals('🌃', String::chr(127747)); + $this->assertEquals('🌃', String::chr(0x1F303)); + $this->assertEquals('', String::chr(2097152)); + } }