From 1977123ea571c2eb2d5661beb57cffdba626ad01 Mon Sep 17 00:00:00 2001 From: Valeriy Streltsov Date: Wed, 24 Apr 2013 13:14:49 +0300 Subject: [PATCH] MDL-39335: add an ord() unicode analog to textlib. --- lib/tests/textlib_test.php | 13 +++++++++++++ lib/textlib.class.php | 29 +++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/lib/tests/textlib_test.php b/lib/tests/textlib_test.php index 35f500dcd04..64f04827188 100644 --- a/lib/tests/textlib_test.php +++ b/lib/tests/textlib_test.php @@ -340,6 +340,19 @@ class core_textlib_testcase extends advanced_testcase { $this->assertSame(textlib::code2utf8(381), 'Ž'); } + /** + * Tests the static utf8ord method + * @return void + */ + public function test_utf8ord() { + $this->assertSame(textlib::utf8ord(''), ord('')); + $this->assertSame(textlib::utf8ord('f'), ord('f')); + $this->assertSame(textlib::utf8ord('α'), 0x03B1); + $this->assertSame(textlib::utf8ord('й'), 0x0439); + $this->assertSame(textlib::utf8ord('𯨟'), 0x2FA1F); + $this->assertSame(textlib::utf8ord('Ž'), 381); + } + /** * Tests the static strtotitle method * @return void diff --git a/lib/textlib.class.php b/lib/textlib.class.php index bddcaa721d6..c91c7e5c1f6 100644 --- a/lib/textlib.class.php +++ b/lib/textlib.class.php @@ -591,6 +591,35 @@ class textlib { return ''; } + /** + * Returns the code of the given UTF-8 character + * + * @param string $utf8char one UTF-8 character + * @return int the code of the given character + */ + public static function utf8ord($utf8char) { + if ($utf8char == '') { + return 0; + } + $ord0 = ord($utf8char{0}); + if ($ord0 >= 0 && $ord0 <= 127) { + return $ord0; + } + $ord1 = ord($utf8char{1}); + if ($ord0 >= 192 && $ord0 <= 223) { + return ($ord0 - 192) * 64 + ($ord1 - 128); + } + $ord2 = ord($utf8char{2}); + if ($ord0 >= 224 && $ord0 <= 239) { + return ($ord0 - 224) * 4096 + ($ord1 - 128) * 64 + ($ord2 - 128); + } + $ord3 = ord($utf8char{3}); + if ($ord0 >= 240 && $ord0 <= 247) { + return ($ord0 - 240) * 262144 + ($ord1 - 128 )* 4096 + ($ord2 - 128) * 64 + ($ord3 - 128); + } + return false; + } + /** * Makes first letter of each word capital - words must be separated by spaces. * Use with care, this function does not work properly in many locales!!!