From 0aca79a4cbcdde2dd519b190c532f9b23ad2f8f9 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Mon, 1 Nov 2021 23:15:10 +0100 Subject: [PATCH] added Strings::ord() --- src/Utils/Strings.php | 18 ++++++++++++++++ tests/Utils/Strings.ord().phpt | 38 ++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 tests/Utils/Strings.ord().phpt diff --git a/src/Utils/Strings.php b/src/Utils/Strings.php index 92c30c991..6f47bb967 100644 --- a/src/Utils/Strings.php +++ b/src/Utils/Strings.php @@ -58,6 +58,24 @@ public static function chr(int $code): string } + /** + * Returns a code point of specific character in UTF-8 (number in range 0x0000..D7FF or 0xE000..10FFFF). + */ + public static function ord(string $c): int + { + if (!extension_loaded('iconv')) { + throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.'); + } + + $tmp = iconv('UTF-8', 'UTF-32BE//IGNORE', $c); + if (!$tmp) { + throw new Nette\InvalidArgumentException('Invalid UTF-8 character "' . ($c === '' ? '' : '\x' . strtoupper(bin2hex($c))) . '".'); + } + + return unpack('N', $tmp)[1]; + } + + /** * Starts the $haystack string with the prefix $needle? */ diff --git a/tests/Utils/Strings.ord().phpt b/tests/Utils/Strings.ord().phpt new file mode 100644 index 000000000..09f6ca2fd --- /dev/null +++ b/tests/Utils/Strings.ord().phpt @@ -0,0 +1,38 @@ +