2# Copyright (C) 2004 Brion Vibber <brion@pobox.com>
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.
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.
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.
21require_once dirname(__FILE__).
'/UtfNormalUtil.php';
28# Load compatibility decompositions on demand if they are needed.
32define(
'UNICODE_HANGUL_FIRST', 0xac00 );
33define(
'UNICODE_HANGUL_LAST', 0xd7a3 );
35define(
'UNICODE_HANGUL_LBASE', 0x1100 );
36define(
'UNICODE_HANGUL_VBASE', 0x1161 );
37define(
'UNICODE_HANGUL_TBASE', 0x11a7 );
39define(
'UNICODE_HANGUL_LCOUNT', 19 );
40define(
'UNICODE_HANGUL_VCOUNT', 21 );
41define(
'UNICODE_HANGUL_TCOUNT', 28 );
48define(
'UNICODE_SURROGATE_FIRST', 0xd800 );
49define(
'UNICODE_SURROGATE_LAST', 0xdfff );
50define(
'UNICODE_MAX', 0x10ffff );
51define(
'UNICODE_REPLACEMENT', 0xfffd );
54define(
'UTF8_HANGUL_FIRST',
"\xea\xb0\x80" );
55define(
'UTF8_HANGUL_LAST',
"\xed\x9e\xa3" );
57define(
'UTF8_HANGUL_LBASE',
"\xe1\x84\x80" );
58define(
'UTF8_HANGUL_VBASE',
"\xe1\x85\xa1" );
59define(
'UTF8_HANGUL_TBASE',
"\xe1\x86\xa7" );
61define(
'UTF8_HANGUL_LEND',
"\xe1\x84\x92" );
62define(
'UTF8_HANGUL_VEND',
"\xe1\x85\xb5" );
63define(
'UTF8_HANGUL_TEND',
"\xe1\x87\x82" );
65define(
'UTF8_SURROGATE_FIRST',
"\xed\xa0\x80" );
66define(
'UTF8_SURROGATE_LAST',
"\xed\xbf\xbf" );
67define(
'UTF8_MAX',
"\xf4\x8f\xbf\xbf" );
68define(
'UTF8_REPLACEMENT',
"\xef\xbf\xbd" );
69#define( 'UTF8_REPLACEMENT', '!' );
71define(
'UTF8_OVERLONG_A',
"\xc1\xbf" );
72define(
'UTF8_OVERLONG_B',
"\xe0\x9f\xbf" );
73define(
'UTF8_OVERLONG_C',
"\xf0\x8f\xbf\xbf" );
75# These two ranges are illegal
76define(
'UTF8_FDD0',
"\xef\xb7\x90" );
77define(
'UTF8_FDEF',
"\xef\xb7\xaf" );
78define(
'UTF8_FFFE',
"\xef\xbf\xbe" );
79define(
'UTF8_FFFF',
"\xef\xbf\xbf" );
81define(
'UTF8_HEAD',
false );
82define(
'UTF8_TAIL',
true );
88define(
'UNORM_NONE', 1 );
89define(
'UNORM_NFD', 2 );
90define(
'UNORM_NFKD', 3 );
91define(
'UNORM_NFC', 4 );
93define(
'UNORM_NFKC', 5 );
94define(
'UNORM_FCD', 6 );
96define(
'NORMALIZE_ICU', function_exists(
'utf8_normalize' ) );
126 # We exclude a few chars that ICU would not.
127 $string = preg_replace(
128 '/[\x00-\x08\x0b\x0c\x0e-\x1f]/',
134 # UnicodeString constructor fails if the string ends with a
135 # head byte. Add a junk char at the end, we'll strip it off.
136 return rtrim( utf8_normalize( $string .
"\x01",
UNORM_NFC ),
"\x01" );
138 # Side effect -- $string has had UTF-8 errors cleaned up.
156 return utf8_normalize( $string,
UNORM_NFC );
173 return utf8_normalize( $string,
UNORM_NFD );
174 elseif( preg_match(
'/[\x80-\xff]/', $string ) )
192 elseif( preg_match(
'/[\x80-\xff]/', $string ) )
210 elseif( preg_match(
'/[\x80-\xff]/', $string ) )
224 require_once( dirname(__FILE__) .
'/UtfNormalData.inc' );
236 # ASCII is always valid NFC!
237 # If it's pure ASCII, let it through.
238 if( !preg_match(
'/[\x80-\xff]/', $string ) )
return true;
242 $len = strlen( $string );
243 for( $i = 0; $i < $len; $i++ ) {
248 } elseif(
$n >= 0xf0 ) {
249 $c = substr( $string, $i, 4 );
251 } elseif(
$n >= 0xe0 ) {
252 $c = substr( $string, $i, 3 );
254 } elseif(
$n >= 0xc0 ) {
255 $c = substr( $string, $i, 2 );
258 if( isset( $utfCheckNFC[$c] ) ) {
259 # If it's NO or MAYBE, bail and do the slow check.
263 # Combining character? We might have to do sorting, at least.
277 # Screen out some characters that eg won't be allowed in XML
278 $string = preg_replace(
'/[\x00-\x08\x0b\x0c\x0e-\x1f]/',
UTF8_REPLACEMENT, $string );
280 # ASCII is always valid NFC!
281 # If we're only ever given plain ASCII, we can avoid the overhead
282 # of initializing the decomposition tables by skipping out early.
283 if( !preg_match(
'/[\x80-\xff]/', $string ) )
return true;
285 static $checkit =
null, $tailBytes =
null, $utfCheckOrCombining =
null;
286 if( !isset( $checkit ) ) {
287 # Load/build some scary lookup tables...
293 # Head bytes for sequences which we should do further validity checks
294 $checkit = array_flip( array_map(
'chr',
295 array( 0xc0, 0xc1, 0xe0, 0xed, 0xef,
296 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
297 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff ) ) );
299 # Each UTF-8 head byte is followed by a certain
300 # number of tail bytes.
301 $tailBytes = array();
302 for(
$n = 0;
$n < 256;
$n++ ) {
305 } elseif(
$n < 0xe0 ) {
307 } elseif(
$n < 0xf0 ) {
309 } elseif(
$n < 0xf8 ) {
311 } elseif(
$n < 0xfc ) {
313 } elseif(
$n < 0xfe ) {
318 $tailBytes[chr(
$n)] = $remaining;
322 # Chop the text into pure-ASCII and non-ASCII areas;
323 # large ASCII parts can be handled much more quickly.
324 # Don't chop up Unicode areas for punctuation, though,
325 # that wastes energy.
328 '/([\x00-\x7f]+|[\x80-\xff][\x00-\x40\x5b-\x5f\x7b-\xff]*)/',
334 foreach( $matches[1] as $str ) {
335 $chunk = strlen( $str );
337 if( $str{0} <
"\x80" ) {
338 # ASCII chunk: guaranteed to be valid UTF-8
339 # and in normal form C, so skip over it.
344 # We'll have to examine the chunk byte by byte to ensure
345 # that it consists of valid UTF-8 sequences, and to see
346 # if any of them might not be normalized.
348 # Since PHP is not the fastest language on earth, some of
349 # this code is a little ugly with inner loop optimizations.
352 $len = $chunk + 1; # Counting
down is faster. I
'm *so* sorry.
354 for( $i = -1; --$len; ) {
355 if( $remaining = $tailBytes[$c = $str{++$i}] ) {
357 $sequence = $head = $c;
359 # Look for the defined number of tail bytes...
360 if( --$len && ( $c = $str{++$i} ) >= "\x80" && $c < "\xc0" ) {
361 # Legal tail bytes are nice.
365 # Premature end of string!
366 # Drop a replacement character into output to
367 # represent the invalid UTF-8 sequence.
368 $replace[] = array( UTF8_REPLACEMENT,
369 $base + $i + 1 - strlen( $sequence ),
370 strlen( $sequence ) );
373 # Illegal tail byte; abandon the sequence.
374 $replace[] = array( UTF8_REPLACEMENT,
375 $base + $i - strlen( $sequence ),
376 strlen( $sequence ) );
377 # Back up and reprocess this byte; it may itself
378 # be a legal ASCII or UTF-8 sequence head.
384 } while( --$remaining );
386 if( isset( $checkit[$head] ) ) {
387 # Do some more detailed validity checks, for
388 # invalid characters and illegal sequences.
389 if( $head == "\xed" ) {
390 # 0xed is relatively frequent in Korean, which
391 # abuts the surrogate area, so we're doing
392 # this check separately to speed things up.
395 # Surrogates are legal only in UTF-16 code.
396 # They are totally forbidden here in UTF-8
399 $base + $i + 1 - strlen( $sequence ),
400 strlen( $sequence ) );
405 # Slower, but rarer checks...
408 #
"Overlong sequences" are those that are syntactically
409 # correct but use more UTF-8 bytes than are necessary to
410 # encode a character. Naïve
string comparisons can be
411 # tricked into failing to see a match
for an ASCII
412 # character,
for instance, which can be a security hole
413 #
if blacklist checks are being used.
418 # U+FFFE and U+FFFF are explicitly forbidden in Unicode.
423 # Unicode has been limited to 21 bits; longer
424 # sequences are not allowed.
428 $base + $i + 1 - strlen( $sequence ),
429 strlen( $sequence ) );
436 if( isset( $utfCheckOrCombining[$sequence] ) ) {
437 # If it's NO or MAYBE, we'll have to rip
438 # the string apart and put it back together.
439 # That's going to be mighty slow.
440 $looksNormal =
false;
443 # The sequence is legal!
445 } elseif( $c <
"\x80" ) {
448 } elseif( $c <
"\xc0" ) {
454 # Don't add if we're continuing a broken sequence;
455 # we already put a replacement character when we looked
456 # at the broken sequence.
457 $replace[] = array(
'', $base + $i, 1 );
460 # Miscellaneous freaks.
467 if( count( $replace ) ) {
468 # There were illegal UTF-8 sequences we need to fix up.
471 foreach( $replace as $rep ) {
472 list( $replacement,
$start, $length ) = $rep;
474 $out .= substr( $string, $last,
$start - $last );
476 $out .= $replacement;
479 if( $last < strlen( $string ) ) {
480 $out .= substr( $string, $last );
487 # These take a string and run the normalization on them, without
488 # checking for validity or any optimization etc. Input must be
496 static function NFC( $string ) {
506 static function NFD( $string ) {
519 static function NFKC( $string ) {
529 static function NFKD( $string ) {
532 require_once(
'UtfNormalDataK.inc' );
551 $len = strlen( $string );
553 for( $i = 0; $i < $len; $i++ ) {
557 # ASCII chars never decompose
561 } elseif(
$n >= 0xf0 ) {
562 $c = substr( $string, $i, 4 );
564 } elseif(
$n >= 0xe0 ) {
565 $c = substr( $string, $i, 3 );
567 } elseif(
$n >= 0xc0 ) {
568 $c = substr( $string, $i, 2 );
571 if( isset( $map[$c] ) ) {
576 # Decompose a hangul syllable into jamo;
577 # hardcoded for three-byte UTF-8 sequence.
578 # A lookup table would be slightly faster,
579 # but adds a lot of memory & disk needs.
581 $index = ( (ord( $c{0} ) & 0x0f) << 12
582 | (ord( $c{1} ) & 0x3f) << 6
583 | (ord( $c{2} ) & 0x3f) )
588 $out .=
"\xe1\x84" . chr( 0x80 +
$l ) .
"\xe1\x85" . chr( 0xa1 + $v );
590 $out .=
"\xe1\x87" . chr( 0x80 +
$t - 25 );
592 $out .=
"\xe1\x86" . chr( 0xa7 +
$t );
613 $len = strlen( $string );
615 $combiners = array();
617 for( $i = 0; $i < $len; $i++ ) {
622 $c = substr( $string, $i, 4 );
624 } elseif(
$n >= 0xe0 ) {
625 $c = substr( $string, $i, 3 );
627 } elseif(
$n >= 0xc0 ) {
628 $c = substr( $string, $i, 2 );
633 if( isset( $combiners[$lastClass] ) ) {
634 $combiners[$lastClass] .= $c;
636 $combiners[$lastClass] = $c;
643 $out .= implode(
'', $combiners );
644 $combiners = array();
651 $out .= implode(
'', $combiners );
667 $len = strlen( $string );
675 for( $i = 0; $i < $len; $i++ ) {
679 # No combining characters here...
686 } elseif(
$n >= 0xf0 ) {
687 $c = substr( $string, $i, 4 );
689 } elseif(
$n >= 0xe0 ) {
690 $c = substr( $string, $i, 3 );
692 } elseif(
$n >= 0xc0 ) {
693 $c = substr( $string, $i, 2 );
696 $pair = $startChar . $c;
699 # A combining char; see what we can do with it
701 if( !empty( $startChar ) &&
702 $lastClass < $class &&
716 if( $lastClass == 0 ) {
722 if(
$n >= $x1 &&
$n <= $x2 ) {
723 # WARNING: Hangul code is painfully slow.
724 # I apologize for this ugly, ugly code; however
725 # performance is even more teh suck if we call
726 # out to nice clean functions. Lookup tables are
727 # marginally faster, but require a lot of space.
734 #$lIndex = utf8ToCodepoint( $startChar ) - UNICODE_HANGUL_LBASE;
735 #$vIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_VBASE;
736 $lIndex = ord( $startChar{2} ) - 0x80;
737 $vIndex = ord( $c{2} ) - 0xa1;
743 # Hardcode the limited-range UTF-8 conversion:
744 $startChar = chr( $hangulPoint >> 12 & 0x0f | 0xe0 ) .
745 chr( $hangulPoint >> 6 & 0x3f | 0x80 ) .
746 chr( $hangulPoint & 0x3f | 0x80 );
754 # $tIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_TBASE;
755 $tIndex = ord( $c{2} ) - 0xa7;
756 if( $tIndex < 0 ) $tIndex = ord( $c{2} ) - 0x80 + (0x11c0 - 0x11a7);
758 # Increment the code point by $tIndex, without
759 # the function overhead of decoding and recoding UTF-8
761 $tail = ord( $startChar{2} ) + $tIndex;
764 $mid = ord( $startChar{1} ) + 1;
766 $startChar{0} = chr( ord( $startChar{0} ) + 1 );
769 $startChar{1} = chr( $mid );
771 $startChar{2} = chr( $tail );
773 # If there's another jamo char after this, *don't* try to merge it.
786 $out .= $startChar . $combining;
798 $len = strlen( $string );
800 for( $i = 0; $i < $len; $i++ ) {
const UNICODE_HANGUL_VCOUNT
global $utfCombiningClass
const UTF8_SURROGATE_FIRST
const UNICODE_HANGUL_LCOUNT
global $utfCompatibilityDecomp
const UNICODE_HANGUL_LBASE
const UNICODE_HANGUL_TBASE
const UNICODE_HANGUL_TCOUNT
global $utfCanonicalDecomp
const UNICODE_HANGUL_FIRST
const UNICODE_HANGUL_NCOUNT
const UNICODE_HANGUL_VBASE
An exception for terminatinating execution or to throw for unit testing.
static toNFD( $string)
Convert a UTF-8 string to normal form D, canonical decomposition.
static fastCombiningSort( $string)
Sorts combining characters into canonical order.
static fastDecompose( $string, $map)
Perform decomposition of a UTF-8 string into either D or KD form (depending on which decomposition ma...
static toNFKC( $string)
Convert a UTF-8 string to normal form KC, compatibility composition.
static loadData()
Load the basic composition data if necessary.
static toNFC( $string)
Convert a UTF-8 string to normal form C, canonical composition.
static cleanUp( $string)
The ultimate convenience function! Clean up invalid UTF-8 sequences, and convert to normal form C,...
static quickIsNFC( $string)
Returns true if the string is definitely in NFC.
static placebo( $string)
This is just used for the benchmark, comparing how long it takes to interate through a string without...
static fastCompose( $string)
Produces canonically composed sequences, i.e.
static quickIsNFCVerify(&$string)
Returns true if the string is definitely in NFC.
static toNFKD( $string)
Convert a UTF-8 string to normal form KD, compatibility decomposition.