Grapheme.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Polyfill\Intl\Grapheme;
  11. \define('SYMFONY_GRAPHEME_CLUSTER_RX', ((float) \PCRE_VERSION < 10 ? (float) \PCRE_VERSION >= 8.32 : (float) \PCRE_VERSION >= 10.39) ? '\X' : Grapheme::GRAPHEME_CLUSTER_RX);
  12. /**
  13. * Partial intl implementation in pure PHP.
  14. *
  15. * Implemented:
  16. * - grapheme_extract - Extract a sequence of grapheme clusters from a text buffer, which must be encoded in UTF-8
  17. * - grapheme_stripos - Find position (in grapheme units) of first occurrence of a case-insensitive string
  18. * - grapheme_stristr - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
  19. * - grapheme_strlen - Get string length in grapheme units
  20. * - grapheme_strpos - Find position (in grapheme units) of first occurrence of a string
  21. * - grapheme_strripos - Find position (in grapheme units) of last occurrence of a case-insensitive string
  22. * - grapheme_strrpos - Find position (in grapheme units) of last occurrence of a string
  23. * - grapheme_strstr - Returns part of haystack string from the first occurrence of needle to the end of haystack
  24. * - grapheme_substr - Return part of a string
  25. * - grapheme_str_split - Splits a string into an array of individual or chunks of graphemes
  26. * - grapheme_levenshtein - Calculate the grapheme-unit Levenshtein distance between two strings
  27. * - grapheme_strrev - Reverse a string by grapheme clusters
  28. *
  29. * @author Nicolas Grekas <p@tchwork.com>
  30. *
  31. * @internal
  32. */
  33. final class Grapheme
  34. {
  35. // (CRLF|([ZWNJ-ZWJ]|T+|L*(LV?V+|LV|LVT)T*|L+|[^Control])[Extend]*|[Control])
  36. // This regular expression is a work around for http://bugs.exim.org/1279
  37. public const GRAPHEME_CLUSTER_RX = '(?:\r\n|(?:[ -~\x{200C}\x{200D}]|[ᆨ-ᇹ]+|[ᄀ-ᅟ]*(?:[가개갸걔거게겨계고과괘괴교구궈궤귀규그긔기까깨꺄꺠꺼께껴꼐꼬꽈꽤꾀꾜꾸꿔꿰뀌뀨끄끠끼나내냐냬너네녀녜노놔놰뇌뇨누눠눼뉘뉴느늬니다대댜댸더데뎌뎨도돠돼되됴두둬뒈뒤듀드듸디따때땨떄떠떼뗘뗴또똬뙈뙤뚀뚜뚸뛔뛰뜌뜨띄띠라래랴럐러레려례로롸뢔뢰료루뤄뤠뤼류르릐리마매먀먜머메며몌모뫄뫠뫼묘무뭐뭬뮈뮤므믜미바배뱌뱨버베벼볘보봐봬뵈뵤부붜붸뷔뷰브븨비빠빼뺘뺴뻐뻬뼈뼤뽀뽜뽸뾔뾰뿌뿨쀄쀠쀼쁘쁴삐사새샤섀서세셔셰소솨쇄쇠쇼수숴쉐쉬슈스싀시싸쌔쌰썌써쎄쎠쎼쏘쏴쐐쐬쑈쑤쒀쒜쒸쓔쓰씌씨아애야얘어에여예오와왜외요우워웨위유으의이자재쟈쟤저제져졔조좌좨죄죠주줘줴쥐쥬즈즤지짜째쨔쨰쩌쩨쪄쪠쪼쫘쫴쬐쬬쭈쭤쮀쮜쮸쯔쯰찌차채챠챼처체쳐쳬초촤쵀최쵸추춰췌취츄츠츼치카캐캬컈커케켜켸코콰쾌쾨쿄쿠쿼퀘퀴큐크킈키타태탸턔터테텨톄토톼퇘퇴툐투퉈퉤튀튜트틔티파패퍄퍠퍼페펴폐포퐈퐤푀표푸풔풰퓌퓨프픠피하해햐햬허헤혀혜호화홰회효후훠훼휘휴흐희히]?[ᅠ-ᆢ]+|[가-힣])[ᆨ-ᇹ]*|[ᄀ-ᅟ]+|[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}])[\p{Mn}\p{Me}\x{09BE}\x{09D7}\x{0B3E}\x{0B57}\x{0BBE}\x{0BD7}\x{0CC2}\x{0CD5}\x{0CD6}\x{0D3E}\x{0D57}\x{0DCF}\x{0DDF}\x{200C}\x{200D}\x{1D165}\x{1D16E}-\x{1D172}]*|[\p{Cc}\p{Cf}\p{Zl}\p{Zp}])';
  38. private const CASE_FOLD = [
  39. ['µ', 'ſ', "\xCD\x85", 'ς', "\xCF\x90", "\xCF\x91", "\xCF\x95", "\xCF\x96", "\xCF\xB0", "\xCF\xB1", "\xCF\xB5", "\xE1\xBA\x9B", "\xE1\xBE\xBE"],
  40. ['μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', "\xE1\xB9\xA1", 'ι'],
  41. ];
  42. public static function grapheme_extract($s, $size, $type = \GRAPHEME_EXTR_COUNT, $start = 0, &$next = 0)
  43. {
  44. if (0 > $start) {
  45. $start = \strlen($s) + $start;
  46. }
  47. if (!\is_scalar($s)) {
  48. $hasError = false;
  49. set_error_handler(static function () use (&$hasError) { $hasError = true; });
  50. $next = substr($s, $start);
  51. restore_error_handler();
  52. if ($hasError) {
  53. substr($s, $start);
  54. $s = '';
  55. } else {
  56. $s = $next;
  57. }
  58. } else {
  59. $s = substr($s, $start);
  60. }
  61. $size = (int) $size;
  62. $type = (int) $type;
  63. $start = (int) $start;
  64. if (\GRAPHEME_EXTR_COUNT !== $type && \GRAPHEME_EXTR_MAXBYTES !== $type && \GRAPHEME_EXTR_MAXCHARS !== $type) {
  65. if (80000 > \PHP_VERSION_ID) {
  66. return false;
  67. }
  68. throw new \ValueError('grapheme_extract(): Argument #3 ($type) must be one of GRAPHEME_EXTR_COUNT, GRAPHEME_EXTR_MAXBYTES, or GRAPHEME_EXTR_MAXCHARS');
  69. }
  70. if (!isset($s[0]) || 0 > $size || 0 > $start) {
  71. return false;
  72. }
  73. if (0 === $size) {
  74. return '';
  75. }
  76. $next = $start;
  77. $s = preg_split('/('.SYMFONY_GRAPHEME_CLUSTER_RX.')/u', "\r\n".$s, $size + 1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE);
  78. if (!isset($s[1])) {
  79. return false;
  80. }
  81. $i = 1;
  82. $ret = '';
  83. do {
  84. if (\GRAPHEME_EXTR_COUNT === $type) {
  85. --$size;
  86. } elseif (\GRAPHEME_EXTR_MAXBYTES === $type) {
  87. $size -= \strlen($s[$i]);
  88. } else {
  89. $size -= iconv_strlen($s[$i], 'UTF-8//IGNORE');
  90. }
  91. if ($size >= 0) {
  92. $ret .= $s[$i];
  93. }
  94. } while (isset($s[++$i]) && $size > 0);
  95. $next += \strlen($ret);
  96. return $ret;
  97. }
  98. public static function grapheme_strlen($s)
  99. {
  100. preg_replace('/'.SYMFONY_GRAPHEME_CLUSTER_RX.'/u', '', $s, -1, $len);
  101. return 0 === $len && '' !== $s ? null : $len;
  102. }
  103. public static function grapheme_substr($s, $start, $len = null)
  104. {
  105. if (null === $len) {
  106. $len = 2147483647;
  107. }
  108. preg_match_all('/'.SYMFONY_GRAPHEME_CLUSTER_RX.'/u', $s, $s);
  109. $slen = \count($s[0]);
  110. $start = (int) $start;
  111. if (0 > $start) {
  112. $start += $slen;
  113. }
  114. if (0 > $start) {
  115. if (\PHP_VERSION_ID < 80000) {
  116. return false;
  117. }
  118. $start = 0;
  119. }
  120. if ($start >= $slen) {
  121. return \PHP_VERSION_ID >= 80000 ? '' : false;
  122. }
  123. $rem = $slen - $start;
  124. if (0 > $len) {
  125. $len += $rem;
  126. }
  127. if (0 === $len) {
  128. return '';
  129. }
  130. if (0 > $len) {
  131. return \PHP_VERSION_ID >= 80000 ? '' : false;
  132. }
  133. if ($len > $rem) {
  134. $len = $rem;
  135. }
  136. return implode('', \array_slice($s[0], $start, $len));
  137. }
  138. public static function grapheme_strpos($s, $needle, $offset = 0)
  139. {
  140. return self::grapheme_position($s, $needle, $offset, 0);
  141. }
  142. public static function grapheme_stripos($s, $needle, $offset = 0)
  143. {
  144. return self::grapheme_position($s, $needle, $offset, 1);
  145. }
  146. public static function grapheme_strrpos($s, $needle, $offset = 0)
  147. {
  148. return self::grapheme_position($s, $needle, $offset, 2);
  149. }
  150. public static function grapheme_strripos($s, $needle, $offset = 0)
  151. {
  152. return self::grapheme_position($s, $needle, $offset, 3);
  153. }
  154. public static function grapheme_stristr($s, $needle, $beforeNeedle = false)
  155. {
  156. return mb_stristr($s, $needle, $beforeNeedle, 'UTF-8');
  157. }
  158. public static function grapheme_strstr($s, $needle, $beforeNeedle = false)
  159. {
  160. return mb_strstr($s, $needle, $beforeNeedle, 'UTF-8');
  161. }
  162. public static function grapheme_str_split($s, $len = 1)
  163. {
  164. if (0 > $len || 1073741823 < $len) {
  165. if (80000 > \PHP_VERSION_ID) {
  166. return false;
  167. }
  168. throw new \ValueError('grapheme_str_split(): Argument #2 ($length) must be greater than 0 and less than or equal to 1073741823.');
  169. }
  170. if ('' === $s) {
  171. return [];
  172. }
  173. if (!preg_match_all('/('.SYMFONY_GRAPHEME_CLUSTER_RX.')/u', $s, $matches)) {
  174. return false;
  175. }
  176. if (1 === $len) {
  177. return $matches[0];
  178. }
  179. $chunks = array_chunk($matches[0], $len);
  180. foreach ($chunks as &$chunk) {
  181. $chunk = implode('', $chunk);
  182. }
  183. return $chunks;
  184. }
  185. public static function grapheme_levenshtein($s1, $s2, $insertion_cost = 1, $replacement_cost = 1, $deletion_cost = 1)
  186. {
  187. if (!preg_match('//u', $s1) || !preg_match('//u', $s2)) {
  188. return false;
  189. }
  190. if (0 > $insertion_cost || 0 > $replacement_cost || 0 > $deletion_cost) {
  191. if (80000 > \PHP_VERSION_ID) {
  192. return false;
  193. }
  194. throw new \ValueError('grapheme_levenshtein(): Argument #3 ($insertion_cost), #4 ($replacement_cost), and #5 ($deletion_cost) must be greater than or equal to 0');
  195. }
  196. preg_match_all('/'.SYMFONY_GRAPHEME_CLUSTER_RX.'/u', $s1, $s1);
  197. preg_match_all('/'.SYMFONY_GRAPHEME_CLUSTER_RX.'/u', $s2, $s2);
  198. $s1 = $s1[0];
  199. $s2 = $s2[0];
  200. $l1 = \count($s1);
  201. $l2 = \count($s2);
  202. if (0 === $l1) {
  203. return $l2 * $insertion_cost;
  204. }
  205. if (0 === $l2) {
  206. return $l1 * $deletion_cost;
  207. }
  208. $dp = array_fill(0, $l1 + 1, array_fill(0, $l2 + 1, 0));
  209. for ($i = 1; $i <= $l1; ++$i) {
  210. $dp[$i][0] = $dp[$i - 1][0] + $deletion_cost;
  211. }
  212. for ($j = 1; $j <= $l2; ++$j) {
  213. $dp[0][$j] = $dp[0][$j - 1] + $insertion_cost;
  214. }
  215. for ($i = 1; $i <= $l1; ++$i) {
  216. for ($j = 1; $j <= $l2; ++$j) {
  217. $cost = ($s1[$i - 1] === $s2[$j - 1]) ? 0 : $replacement_cost;
  218. $dp[$i][$j] = min($dp[$i - 1][$j] + $deletion_cost, $dp[$i][$j - 1] + $insertion_cost, $dp[$i - 1][$j - 1] + $cost);
  219. }
  220. }
  221. return $dp[$l1][$l2];
  222. }
  223. private static function grapheme_position($s, $needle, $offset, $mode)
  224. {
  225. $needle = (string) $needle;
  226. if (80000 > \PHP_VERSION_ID && !preg_match('/./us', $needle)) {
  227. return false;
  228. }
  229. $s = (string) $s;
  230. if (!preg_match('/./us', $s)) {
  231. return false;
  232. }
  233. if ($offset > 0) {
  234. $s = self::grapheme_substr($s, $offset);
  235. } elseif ($offset < 0) {
  236. if (2 > $mode) {
  237. $offset += self::grapheme_strlen($s);
  238. $s = self::grapheme_substr($s, $offset);
  239. if (0 > $offset) {
  240. $offset = 0;
  241. }
  242. } elseif (0 > $offset += self::grapheme_strlen($needle)) {
  243. $s = self::grapheme_substr($s, 0, $offset);
  244. $offset = 0;
  245. } else {
  246. $offset = 0;
  247. }
  248. }
  249. // As UTF-8 is self-synchronizing, and we have ensured the strings are valid UTF-8,
  250. // we can use normal binary string functions here. For case-insensitive searches,
  251. // case fold the strings first.
  252. $caseInsensitive = $mode & 1;
  253. $reverse = $mode & 2;
  254. if ($caseInsensitive) {
  255. // Use the same case folding mode as mbstring does for mb_stripos().
  256. // Stick to SIMPLE case folding to avoid changing the length of the string, which
  257. // might result in offsets being shifted.
  258. $mode = \defined('MB_CASE_FOLD_SIMPLE') ? \MB_CASE_FOLD_SIMPLE : \MB_CASE_LOWER;
  259. $s = mb_convert_case($s, $mode, 'UTF-8');
  260. $needle = mb_convert_case($needle, $mode, 'UTF-8');
  261. if (!\defined('MB_CASE_FOLD_SIMPLE')) {
  262. $s = str_replace(self::CASE_FOLD[0], self::CASE_FOLD[1], $s);
  263. $needle = str_replace(self::CASE_FOLD[0], self::CASE_FOLD[1], $needle);
  264. }
  265. }
  266. if ($reverse) {
  267. $needlePos = strrpos($s, $needle);
  268. } else {
  269. $needlePos = strpos($s, $needle);
  270. }
  271. return false !== $needlePos ? self::grapheme_strlen(substr($s, 0, $needlePos)) + $offset : false;
  272. }
  273. public static function grapheme_strrev(string $string)
  274. {
  275. $units = grapheme_str_split($string);
  276. if (false === $units) {
  277. return false;
  278. }
  279. return implode('', array_reverse($units));
  280. }
  281. }