UtfNormal.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. <?php
  2. # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
  3. # http://www.mediawiki.org/
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License along
  16. # with this program; if not, write to the Free Software Foundation, Inc.,
  17. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. # http://www.gnu.org/copyleft/gpl.html
  19. /**
  20. * @defgroup UtfNormal UtfNormal
  21. */
  22. /** */
  23. require_once dirname(__FILE__).'/UtfNormalUtil.php';
  24. global $utfCombiningClass, $utfCanonicalComp, $utfCanonicalDecomp;
  25. $utfCombiningClass = NULL;
  26. $utfCanonicalComp = NULL;
  27. $utfCanonicalDecomp = NULL;
  28. # Load compatibility decompositions on demand if they are needed.
  29. global $utfCompatibilityDecomp;
  30. $utfCompatibilityDecomp = NULL;
  31. /**
  32. * For using the ICU wrapper
  33. */
  34. define( 'UNORM_NONE', 1 );
  35. define( 'UNORM_NFD', 2 );
  36. define( 'UNORM_NFKD', 3 );
  37. define( 'UNORM_NFC', 4 );
  38. define( 'UNORM_DEFAULT', UNORM_NFC );
  39. define( 'UNORM_NFKC', 5 );
  40. define( 'UNORM_FCD', 6 );
  41. define( 'NORMALIZE_ICU', function_exists( 'utf8_normalize' ) );
  42. /**
  43. * Unicode normalization routines for working with UTF-8 strings.
  44. * Currently assumes that input strings are valid UTF-8!
  45. *
  46. * Not as fast as I'd like, but should be usable for most purposes.
  47. * UtfNormal::toNFC() will bail early if given ASCII text or text
  48. * it can quickly deterimine is already normalized.
  49. *
  50. * All functions can be called static.
  51. *
  52. * See description of forms at http://www.unicode.org/reports/tr15/
  53. *
  54. * @ingroup UtfNormal
  55. */
  56. class UtfNormal {
  57. /**
  58. * The ultimate convenience function! Clean up invalid UTF-8 sequences,
  59. * and convert to normal form C, canonical composition.
  60. *
  61. * Fast return for pure ASCII strings; some lesser optimizations for
  62. * strings containing only known-good characters. Not as fast as toNFC().
  63. *
  64. * @param $string String: a UTF-8 string
  65. * @return string a clean, shiny, normalized UTF-8 string
  66. */
  67. static function cleanUp( $string ) {
  68. if( NORMALIZE_ICU ) {
  69. # We exclude a few chars that ICU would not.
  70. $string = preg_replace(
  71. '/[\x00-\x08\x0b\x0c\x0e-\x1f]/',
  72. UTF8_REPLACEMENT,
  73. $string );
  74. $string = str_replace( UTF8_FFFE, UTF8_REPLACEMENT, $string );
  75. $string = str_replace( UTF8_FFFF, UTF8_REPLACEMENT, $string );
  76. # UnicodeString constructor fails if the string ends with a
  77. # head byte. Add a junk char at the end, we'll strip it off.
  78. return rtrim( utf8_normalize( $string . "\x01", UNORM_NFC ), "\x01" );
  79. } elseif( UtfNormal::quickIsNFCVerify( $string ) ) {
  80. # Side effect -- $string has had UTF-8 errors cleaned up.
  81. return $string;
  82. } else {
  83. return UtfNormal::NFC( $string );
  84. }
  85. }
  86. /**
  87. * Convert a UTF-8 string to normal form C, canonical composition.
  88. * Fast return for pure ASCII strings; some lesser optimizations for
  89. * strings containing only known-good characters.
  90. *
  91. * @param $string String: a valid UTF-8 string. Input is not validated.
  92. * @return string a UTF-8 string in normal form C
  93. */
  94. static function toNFC( $string ) {
  95. if( NORMALIZE_ICU )
  96. return utf8_normalize( $string, UNORM_NFC );
  97. elseif( UtfNormal::quickIsNFC( $string ) )
  98. return $string;
  99. else
  100. return UtfNormal::NFC( $string );
  101. }
  102. /**
  103. * Convert a UTF-8 string to normal form D, canonical decomposition.
  104. * Fast return for pure ASCII strings.
  105. *
  106. * @param $string String: a valid UTF-8 string. Input is not validated.
  107. * @return string a UTF-8 string in normal form D
  108. */
  109. static function toNFD( $string ) {
  110. if( NORMALIZE_ICU )
  111. return utf8_normalize( $string, UNORM_NFD );
  112. elseif( preg_match( '/[\x80-\xff]/', $string ) )
  113. return UtfNormal::NFD( $string );
  114. else
  115. return $string;
  116. }
  117. /**
  118. * Convert a UTF-8 string to normal form KC, compatibility composition.
  119. * This may cause irreversible information loss, use judiciously.
  120. * Fast return for pure ASCII strings.
  121. *
  122. * @param $string String: a valid UTF-8 string. Input is not validated.
  123. * @return string a UTF-8 string in normal form KC
  124. */
  125. static function toNFKC( $string ) {
  126. if( NORMALIZE_ICU )
  127. return utf8_normalize( $string, UNORM_NFKC );
  128. elseif( preg_match( '/[\x80-\xff]/', $string ) )
  129. return UtfNormal::NFKC( $string );
  130. else
  131. return $string;
  132. }
  133. /**
  134. * Convert a UTF-8 string to normal form KD, compatibility decomposition.
  135. * This may cause irreversible information loss, use judiciously.
  136. * Fast return for pure ASCII strings.
  137. *
  138. * @param $string String: a valid UTF-8 string. Input is not validated.
  139. * @return string a UTF-8 string in normal form KD
  140. */
  141. static function toNFKD( $string ) {
  142. if( NORMALIZE_ICU )
  143. return utf8_normalize( $string, UNORM_NFKD );
  144. elseif( preg_match( '/[\x80-\xff]/', $string ) )
  145. return UtfNormal::NFKD( $string );
  146. else
  147. return $string;
  148. }
  149. /**
  150. * Load the basic composition data if necessary
  151. * @private
  152. */
  153. static function loadData() {
  154. global $utfCombiningClass;
  155. if( !isset( $utfCombiningClass ) ) {
  156. require_once( dirname(__FILE__) . '/UtfNormalData.inc' );
  157. }
  158. }
  159. /**
  160. * Returns true if the string is _definitely_ in NFC.
  161. * Returns false if not or uncertain.
  162. * @param $string String: a valid UTF-8 string. Input is not validated.
  163. * @return bool
  164. */
  165. static function quickIsNFC( $string ) {
  166. # ASCII is always valid NFC!
  167. # If it's pure ASCII, let it through.
  168. if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
  169. UtfNormal::loadData();
  170. global $utfCheckNFC, $utfCombiningClass;
  171. $len = strlen( $string );
  172. for( $i = 0; $i < $len; $i++ ) {
  173. $c = $string{$i};
  174. $n = ord( $c );
  175. if( $n < 0x80 ) {
  176. continue;
  177. } elseif( $n >= 0xf0 ) {
  178. $c = substr( $string, $i, 4 );
  179. $i += 3;
  180. } elseif( $n >= 0xe0 ) {
  181. $c = substr( $string, $i, 3 );
  182. $i += 2;
  183. } elseif( $n >= 0xc0 ) {
  184. $c = substr( $string, $i, 2 );
  185. $i++;
  186. }
  187. if( isset( $utfCheckNFC[$c] ) ) {
  188. # If it's NO or MAYBE, bail and do the slow check.
  189. return false;
  190. }
  191. if( isset( $utfCombiningClass[$c] ) ) {
  192. # Combining character? We might have to do sorting, at least.
  193. return false;
  194. }
  195. }
  196. return true;
  197. }
  198. /**
  199. * Returns true if the string is _definitely_ in NFC.
  200. * Returns false if not or uncertain.
  201. * @param $string String: a UTF-8 string, altered on output to be valid UTF-8 safe for XML.
  202. */
  203. static function quickIsNFCVerify( &$string ) {
  204. # Screen out some characters that eg won't be allowed in XML
  205. $string = preg_replace( '/[\x00-\x08\x0b\x0c\x0e-\x1f]/', UTF8_REPLACEMENT, $string );
  206. # ASCII is always valid NFC!
  207. # If we're only ever given plain ASCII, we can avoid the overhead
  208. # of initializing the decomposition tables by skipping out early.
  209. if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
  210. static $checkit = null, $tailBytes = null, $utfCheckOrCombining = null;
  211. if( !isset( $checkit ) ) {
  212. # Load/build some scary lookup tables...
  213. UtfNormal::loadData();
  214. global $utfCheckNFC, $utfCombiningClass;
  215. $utfCheckOrCombining = array_merge( $utfCheckNFC, $utfCombiningClass );
  216. # Head bytes for sequences which we should do further validity checks
  217. $checkit = array_flip( array_map( 'chr',
  218. array( 0xc0, 0xc1, 0xe0, 0xed, 0xef,
  219. 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
  220. 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff ) ) );
  221. # Each UTF-8 head byte is followed by a certain
  222. # number of tail bytes.
  223. $tailBytes = array();
  224. for( $n = 0; $n < 256; $n++ ) {
  225. if( $n < 0xc0 ) {
  226. $remaining = 0;
  227. } elseif( $n < 0xe0 ) {
  228. $remaining = 1;
  229. } elseif( $n < 0xf0 ) {
  230. $remaining = 2;
  231. } elseif( $n < 0xf8 ) {
  232. $remaining = 3;
  233. } elseif( $n < 0xfc ) {
  234. $remaining = 4;
  235. } elseif( $n < 0xfe ) {
  236. $remaining = 5;
  237. } else {
  238. $remaining = 0;
  239. }
  240. $tailBytes[chr($n)] = $remaining;
  241. }
  242. }
  243. # Chop the text into pure-ASCII and non-ASCII areas;
  244. # large ASCII parts can be handled much more quickly.
  245. # Don't chop up Unicode areas for punctuation, though,
  246. # that wastes energy.
  247. $matches = array();
  248. preg_match_all(
  249. '/([\x00-\x7f]+|[\x80-\xff][\x00-\x40\x5b-\x5f\x7b-\xff]*)/',
  250. $string, $matches );
  251. $looksNormal = true;
  252. $base = 0;
  253. $replace = array();
  254. foreach( $matches[1] as $str ) {
  255. $chunk = strlen( $str );
  256. if( $str{0} < "\x80" ) {
  257. # ASCII chunk: guaranteed to be valid UTF-8
  258. # and in normal form C, so skip over it.
  259. $base += $chunk;
  260. continue;
  261. }
  262. # We'll have to examine the chunk byte by byte to ensure
  263. # that it consists of valid UTF-8 sequences, and to see
  264. # if any of them might not be normalized.
  265. #
  266. # Since PHP is not the fastest language on earth, some of
  267. # this code is a little ugly with inner loop optimizations.
  268. $head = '';
  269. $len = $chunk + 1; # Counting down is faster. I'm *so* sorry.
  270. for( $i = -1; --$len; ) {
  271. if( $remaining = $tailBytes[$c = $str{++$i}] ) {
  272. # UTF-8 head byte!
  273. $sequence = $head = $c;
  274. do {
  275. # Look for the defined number of tail bytes...
  276. if( --$len && ( $c = $str{++$i} ) >= "\x80" && $c < "\xc0" ) {
  277. # Legal tail bytes are nice.
  278. $sequence .= $c;
  279. } else {
  280. if( 0 == $len ) {
  281. # Premature end of string!
  282. # Drop a replacement character into output to
  283. # represent the invalid UTF-8 sequence.
  284. $replace[] = array( UTF8_REPLACEMENT,
  285. $base + $i + 1 - strlen( $sequence ),
  286. strlen( $sequence ) );
  287. break 2;
  288. } else {
  289. # Illegal tail byte; abandon the sequence.
  290. $replace[] = array( UTF8_REPLACEMENT,
  291. $base + $i - strlen( $sequence ),
  292. strlen( $sequence ) );
  293. # Back up and reprocess this byte; it may itself
  294. # be a legal ASCII or UTF-8 sequence head.
  295. --$i;
  296. ++$len;
  297. continue 2;
  298. }
  299. }
  300. } while( --$remaining );
  301. if( isset( $checkit[$head] ) ) {
  302. # Do some more detailed validity checks, for
  303. # invalid characters and illegal sequences.
  304. if( $head == "\xed" ) {
  305. # 0xed is relatively frequent in Korean, which
  306. # abuts the surrogate area, so we're doing
  307. # this check separately to speed things up.
  308. if( $sequence >= UTF8_SURROGATE_FIRST ) {
  309. # Surrogates are legal only in UTF-16 code.
  310. # They are totally forbidden here in UTF-8
  311. # utopia.
  312. $replace[] = array( UTF8_REPLACEMENT,
  313. $base + $i + 1 - strlen( $sequence ),
  314. strlen( $sequence ) );
  315. $head = '';
  316. continue;
  317. }
  318. } else {
  319. # Slower, but rarer checks...
  320. $n = ord( $head );
  321. if(
  322. # "Overlong sequences" are those that are syntactically
  323. # correct but use more UTF-8 bytes than are necessary to
  324. # encode a character. Naïve string comparisons can be
  325. # tricked into failing to see a match for an ASCII
  326. # character, for instance, which can be a security hole
  327. # if blacklist checks are being used.
  328. ($n < 0xc2 && $sequence <= UTF8_OVERLONG_A)
  329. || ($n == 0xe0 && $sequence <= UTF8_OVERLONG_B)
  330. || ($n == 0xf0 && $sequence <= UTF8_OVERLONG_C)
  331. # U+FFFE and U+FFFF are explicitly forbidden in Unicode.
  332. || ($n == 0xef &&
  333. ($sequence == UTF8_FFFE)
  334. || ($sequence == UTF8_FFFF) )
  335. # Unicode has been limited to 21 bits; longer
  336. # sequences are not allowed.
  337. || ($n >= 0xf0 && $sequence > UTF8_MAX) ) {
  338. $replace[] = array( UTF8_REPLACEMENT,
  339. $base + $i + 1 - strlen( $sequence ),
  340. strlen( $sequence ) );
  341. $head = '';
  342. continue;
  343. }
  344. }
  345. }
  346. if( isset( $utfCheckOrCombining[$sequence] ) ) {
  347. # If it's NO or MAYBE, we'll have to rip
  348. # the string apart and put it back together.
  349. # That's going to be mighty slow.
  350. $looksNormal = false;
  351. }
  352. # The sequence is legal!
  353. $head = '';
  354. } elseif( $c < "\x80" ) {
  355. # ASCII byte.
  356. $head = '';
  357. } elseif( $c < "\xc0" ) {
  358. # Illegal tail bytes
  359. if( $head == '' ) {
  360. # Out of the blue!
  361. $replace[] = array( UTF8_REPLACEMENT, $base + $i, 1 );
  362. } else {
  363. # Don't add if we're continuing a broken sequence;
  364. # we already put a replacement character when we looked
  365. # at the broken sequence.
  366. $replace[] = array( '', $base + $i, 1 );
  367. }
  368. } else {
  369. # Miscellaneous freaks.
  370. $replace[] = array( UTF8_REPLACEMENT, $base + $i, 1 );
  371. $head = '';
  372. }
  373. }
  374. $base += $chunk;
  375. }
  376. if( count( $replace ) ) {
  377. # There were illegal UTF-8 sequences we need to fix up.
  378. $out = '';
  379. $last = 0;
  380. foreach( $replace as $rep ) {
  381. list( $replacement, $start, $length ) = $rep;
  382. if( $last < $start ) {
  383. $out .= substr( $string, $last, $start - $last );
  384. }
  385. $out .= $replacement;
  386. $last = $start + $length;
  387. }
  388. if( $last < strlen( $string ) ) {
  389. $out .= substr( $string, $last );
  390. }
  391. $string = $out;
  392. }
  393. return $looksNormal;
  394. }
  395. # These take a string and run the normalization on them, without
  396. # checking for validity or any optimization etc. Input must be
  397. # VALID UTF-8!
  398. /**
  399. * @param $string string
  400. * @return string
  401. * @private
  402. */
  403. static function NFC( $string ) {
  404. return UtfNormal::fastCompose( UtfNormal::NFD( $string ) );
  405. }
  406. /**
  407. * @param $string string
  408. * @return string
  409. * @private
  410. */
  411. static function NFD( $string ) {
  412. UtfNormal::loadData();
  413. global $utfCanonicalDecomp;
  414. return UtfNormal::fastCombiningSort(
  415. UtfNormal::fastDecompose( $string, $utfCanonicalDecomp ) );
  416. }
  417. /**
  418. * @param $string string
  419. * @return string
  420. * @private
  421. */
  422. static function NFKC( $string ) {
  423. return UtfNormal::fastCompose( UtfNormal::NFKD( $string ) );
  424. }
  425. /**
  426. * @param $string string
  427. * @return string
  428. * @private
  429. */
  430. static function NFKD( $string ) {
  431. global $utfCompatibilityDecomp;
  432. if( !isset( $utfCompatibilityDecomp ) ) {
  433. require_once( 'UtfNormalDataK.inc' );
  434. }
  435. return UtfNormal::fastCombiningSort(
  436. UtfNormal::fastDecompose( $string, $utfCompatibilityDecomp ) );
  437. }
  438. /**
  439. * Perform decomposition of a UTF-8 string into either D or KD form
  440. * (depending on which decomposition map is passed to us).
  441. * Input is assumed to be *valid* UTF-8. Invalid code will break.
  442. * @private
  443. * @param $string String: valid UTF-8 string
  444. * @param $map Array: hash of expanded decomposition map
  445. * @return string a UTF-8 string decomposed, not yet normalized (needs sorting)
  446. */
  447. static function fastDecompose( $string, $map ) {
  448. UtfNormal::loadData();
  449. $len = strlen( $string );
  450. $out = '';
  451. for( $i = 0; $i < $len; $i++ ) {
  452. $c = $string{$i};
  453. $n = ord( $c );
  454. if( $n < 0x80 ) {
  455. # ASCII chars never decompose
  456. # THEY ARE IMMORTAL
  457. $out .= $c;
  458. continue;
  459. } elseif( $n >= 0xf0 ) {
  460. $c = substr( $string, $i, 4 );
  461. $i += 3;
  462. } elseif( $n >= 0xe0 ) {
  463. $c = substr( $string, $i, 3 );
  464. $i += 2;
  465. } elseif( $n >= 0xc0 ) {
  466. $c = substr( $string, $i, 2 );
  467. $i++;
  468. }
  469. if( isset( $map[$c] ) ) {
  470. $out .= $map[$c];
  471. continue;
  472. } else {
  473. if( $c >= UTF8_HANGUL_FIRST && $c <= UTF8_HANGUL_LAST ) {
  474. # Decompose a hangul syllable into jamo;
  475. # hardcoded for three-byte UTF-8 sequence.
  476. # A lookup table would be slightly faster,
  477. # but adds a lot of memory & disk needs.
  478. #
  479. $index = ( (ord( $c{0} ) & 0x0f) << 12
  480. | (ord( $c{1} ) & 0x3f) << 6
  481. | (ord( $c{2} ) & 0x3f) )
  482. - UNICODE_HANGUL_FIRST;
  483. $l = intval( $index / UNICODE_HANGUL_NCOUNT );
  484. $v = intval( ($index % UNICODE_HANGUL_NCOUNT) / UNICODE_HANGUL_TCOUNT);
  485. $t = $index % UNICODE_HANGUL_TCOUNT;
  486. $out .= "\xe1\x84" . chr( 0x80 + $l ) . "\xe1\x85" . chr( 0xa1 + $v );
  487. if( $t >= 25 ) {
  488. $out .= "\xe1\x87" . chr( 0x80 + $t - 25 );
  489. } elseif( $t ) {
  490. $out .= "\xe1\x86" . chr( 0xa7 + $t );
  491. }
  492. continue;
  493. }
  494. }
  495. $out .= $c;
  496. }
  497. return $out;
  498. }
  499. /**
  500. * Sorts combining characters into canonical order. This is the
  501. * final step in creating decomposed normal forms D and KD.
  502. * @private
  503. * @param $string String: a valid, decomposed UTF-8 string. Input is not validated.
  504. * @return string a UTF-8 string with combining characters sorted in canonical order
  505. */
  506. static function fastCombiningSort( $string ) {
  507. UtfNormal::loadData();
  508. global $utfCombiningClass;
  509. $len = strlen( $string );
  510. $out = '';
  511. $combiners = array();
  512. $lastClass = -1;
  513. for( $i = 0; $i < $len; $i++ ) {
  514. $c = $string{$i};
  515. $n = ord( $c );
  516. if( $n >= 0x80 ) {
  517. if( $n >= 0xf0 ) {
  518. $c = substr( $string, $i, 4 );
  519. $i += 3;
  520. } elseif( $n >= 0xe0 ) {
  521. $c = substr( $string, $i, 3 );
  522. $i += 2;
  523. } elseif( $n >= 0xc0 ) {
  524. $c = substr( $string, $i, 2 );
  525. $i++;
  526. }
  527. if( isset( $utfCombiningClass[$c] ) ) {
  528. $lastClass = $utfCombiningClass[$c];
  529. if( isset( $combiners[$lastClass] ) ) {
  530. $combiners[$lastClass] .= $c;
  531. } else {
  532. $combiners[$lastClass] = $c;
  533. }
  534. continue;
  535. }
  536. }
  537. if( $lastClass ) {
  538. ksort( $combiners );
  539. $out .= implode( '', $combiners );
  540. $combiners = array();
  541. }
  542. $out .= $c;
  543. $lastClass = 0;
  544. }
  545. if( $lastClass ) {
  546. ksort( $combiners );
  547. $out .= implode( '', $combiners );
  548. }
  549. return $out;
  550. }
  551. /**
  552. * Produces canonically composed sequences, i.e. normal form C or KC.
  553. *
  554. * @private
  555. * @param $string String: a valid UTF-8 string in sorted normal form D or KD. Input is not validated.
  556. * @return string a UTF-8 string with canonical precomposed characters used where possible
  557. */
  558. static function fastCompose( $string ) {
  559. UtfNormal::loadData();
  560. global $utfCanonicalComp, $utfCombiningClass;
  561. $len = strlen( $string );
  562. $out = '';
  563. $lastClass = -1;
  564. $lastHangul = 0;
  565. $startChar = '';
  566. $combining = '';
  567. $x1 = ord(substr(UTF8_HANGUL_VBASE,0,1));
  568. $x2 = ord(substr(UTF8_HANGUL_TEND,0,1));
  569. for( $i = 0; $i < $len; $i++ ) {
  570. $c = $string{$i};
  571. $n = ord( $c );
  572. if( $n < 0x80 ) {
  573. # No combining characters here...
  574. $out .= $startChar;
  575. $out .= $combining;
  576. $startChar = $c;
  577. $combining = '';
  578. $lastClass = 0;
  579. continue;
  580. } elseif( $n >= 0xf0 ) {
  581. $c = substr( $string, $i, 4 );
  582. $i += 3;
  583. } elseif( $n >= 0xe0 ) {
  584. $c = substr( $string, $i, 3 );
  585. $i += 2;
  586. } elseif( $n >= 0xc0 ) {
  587. $c = substr( $string, $i, 2 );
  588. $i++;
  589. }
  590. $pair = $startChar . $c;
  591. if( $n > 0x80 ) {
  592. if( isset( $utfCombiningClass[$c] ) ) {
  593. # A combining char; see what we can do with it
  594. $class = $utfCombiningClass[$c];
  595. if( !empty( $startChar ) &&
  596. $lastClass < $class &&
  597. $class > 0 &&
  598. isset( $utfCanonicalComp[$pair] ) ) {
  599. $startChar = $utfCanonicalComp[$pair];
  600. $class = 0;
  601. } else {
  602. $combining .= $c;
  603. }
  604. $lastClass = $class;
  605. $lastHangul = 0;
  606. continue;
  607. }
  608. }
  609. # New start char
  610. if( $lastClass == 0 ) {
  611. if( isset( $utfCanonicalComp[$pair] ) ) {
  612. $startChar = $utfCanonicalComp[$pair];
  613. $lastHangul = 0;
  614. continue;
  615. }
  616. if( $n >= $x1 && $n <= $x2 ) {
  617. # WARNING: Hangul code is painfully slow.
  618. # I apologize for this ugly, ugly code; however
  619. # performance is even more teh suck if we call
  620. # out to nice clean functions. Lookup tables are
  621. # marginally faster, but require a lot of space.
  622. #
  623. if( $c >= UTF8_HANGUL_VBASE &&
  624. $c <= UTF8_HANGUL_VEND &&
  625. $startChar >= UTF8_HANGUL_LBASE &&
  626. $startChar <= UTF8_HANGUL_LEND ) {
  627. #
  628. #$lIndex = utf8ToCodepoint( $startChar ) - UNICODE_HANGUL_LBASE;
  629. #$vIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_VBASE;
  630. $lIndex = ord( $startChar{2} ) - 0x80;
  631. $vIndex = ord( $c{2} ) - 0xa1;
  632. $hangulPoint = UNICODE_HANGUL_FIRST +
  633. UNICODE_HANGUL_TCOUNT *
  634. (UNICODE_HANGUL_VCOUNT * $lIndex + $vIndex);
  635. # Hardcode the limited-range UTF-8 conversion:
  636. $startChar = chr( $hangulPoint >> 12 & 0x0f | 0xe0 ) .
  637. chr( $hangulPoint >> 6 & 0x3f | 0x80 ) .
  638. chr( $hangulPoint & 0x3f | 0x80 );
  639. $lastHangul = 0;
  640. continue;
  641. } elseif( $c >= UTF8_HANGUL_TBASE &&
  642. $c <= UTF8_HANGUL_TEND &&
  643. $startChar >= UTF8_HANGUL_FIRST &&
  644. $startChar <= UTF8_HANGUL_LAST &&
  645. !$lastHangul ) {
  646. # $tIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_TBASE;
  647. $tIndex = ord( $c{2} ) - 0xa7;
  648. if( $tIndex < 0 ) $tIndex = ord( $c{2} ) - 0x80 + (0x11c0 - 0x11a7);
  649. # Increment the code point by $tIndex, without
  650. # the function overhead of decoding and recoding UTF-8
  651. #
  652. $tail = ord( $startChar{2} ) + $tIndex;
  653. if( $tail > 0xbf ) {
  654. $tail -= 0x40;
  655. $mid = ord( $startChar{1} ) + 1;
  656. if( $mid > 0xbf ) {
  657. $startChar{0} = chr( ord( $startChar{0} ) + 1 );
  658. $mid -= 0x40;
  659. }
  660. $startChar{1} = chr( $mid );
  661. }
  662. $startChar{2} = chr( $tail );
  663. # If there's another jamo char after this, *don't* try to merge it.
  664. $lastHangul = 1;
  665. continue;
  666. }
  667. }
  668. }
  669. $out .= $startChar;
  670. $out .= $combining;
  671. $startChar = $c;
  672. $combining = '';
  673. $lastClass = 0;
  674. $lastHangul = 0;
  675. }
  676. $out .= $startChar . $combining;
  677. return $out;
  678. }
  679. /**
  680. * This is just used for the benchmark, comparing how long it takes to
  681. * interate through a string without really doing anything of substance.
  682. * @param $string string
  683. * @return string
  684. */
  685. static function placebo( $string ) {
  686. $len = strlen( $string );
  687. $out = '';
  688. for( $i = 0; $i < $len; $i++ ) {
  689. $out .= $string{$i};
  690. }
  691. return $out;
  692. }
  693. }