/
UTF8.php
12899 lines (11472 loc) · 415 KB
/
UTF8.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace voku\helper;
final class UTF8
{
/**
* (CRLF|([ZWNJ-ZWJ]|T+|L*(LV?V+|LV|LVT)T*|L+|[^Control])[Extend]*|[Control])
* This regular expression is a work around for http://bugs.exim.org/1279
*/
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}])";
/**
* Bom => Byte-Length
*
* INFO: https://en.wikipedia.org/wiki/Byte_order_mark
*
* @var array
*/
private static $BOM = [
"\xef\xbb\xbf" => 3, // UTF-8 BOM
'' => 6, // UTF-8 BOM as "WINDOWS-1252" (one char has [maybe] more then one byte ...)
"\x00\x00\xfe\xff" => 4, // UTF-32 (BE) BOM
' þÿ' => 6, // UTF-32 (BE) BOM as "WINDOWS-1252"
"\xff\xfe\x00\x00" => 4, // UTF-32 (LE) BOM
'ÿþ ' => 6, // UTF-32 (LE) BOM as "WINDOWS-1252"
"\xfe\xff" => 2, // UTF-16 (BE) BOM
'þÿ' => 4, // UTF-16 (BE) BOM as "WINDOWS-1252"
"\xff\xfe" => 2, // UTF-16 (LE) BOM
'ÿþ' => 4, // UTF-16 (LE) BOM as "WINDOWS-1252"
];
/**
* Numeric code point => UTF-8 Character
*
* url: http://www.w3schools.com/charsets/ref_utf_punctuation.asp
*
* @var array
*/
private static $WHITESPACE = [
// NUL Byte
0 => "\x0",
// Tab
9 => "\x9",
// New Line
10 => "\xa",
// Vertical Tab
11 => "\xb",
// Carriage Return
13 => "\xd",
// Ordinary Space
32 => "\x20",
// NO-BREAK SPACE
160 => "\xc2\xa0",
// OGHAM SPACE MARK
5760 => "\xe1\x9a\x80",
// MONGOLIAN VOWEL SEPARATOR
6158 => "\xe1\xa0\x8e",
// EN QUAD
8192 => "\xe2\x80\x80",
// EM QUAD
8193 => "\xe2\x80\x81",
// EN SPACE
8194 => "\xe2\x80\x82",
// EM SPACE
8195 => "\xe2\x80\x83",
// THREE-PER-EM SPACE
8196 => "\xe2\x80\x84",
// FOUR-PER-EM SPACE
8197 => "\xe2\x80\x85",
// SIX-PER-EM SPACE
8198 => "\xe2\x80\x86",
// FIGURE SPACE
8199 => "\xe2\x80\x87",
// PUNCTUATION SPACE
8200 => "\xe2\x80\x88",
// THIN SPACE
8201 => "\xe2\x80\x89",
//HAIR SPACE
8202 => "\xe2\x80\x8a",
// LINE SEPARATOR
8232 => "\xe2\x80\xa8",
// PARAGRAPH SEPARATOR
8233 => "\xe2\x80\xa9",
// NARROW NO-BREAK SPACE
8239 => "\xe2\x80\xaf",
// MEDIUM MATHEMATICAL SPACE
8287 => "\xe2\x81\x9f",
// HALFWIDTH HANGUL FILLER
65440 => "\xef\xbe\xa0",
// IDEOGRAPHIC SPACE
12288 => "\xe3\x80\x80",
];
/**
* @var array
*/
private static $WHITESPACE_TABLE = [
'SPACE' => "\x20",
'NO-BREAK SPACE' => "\xc2\xa0",
'OGHAM SPACE MARK' => "\xe1\x9a\x80",
'EN QUAD' => "\xe2\x80\x80",
'EM QUAD' => "\xe2\x80\x81",
'EN SPACE' => "\xe2\x80\x82",
'EM SPACE' => "\xe2\x80\x83",
'THREE-PER-EM SPACE' => "\xe2\x80\x84",
'FOUR-PER-EM SPACE' => "\xe2\x80\x85",
'SIX-PER-EM SPACE' => "\xe2\x80\x86",
'FIGURE SPACE' => "\xe2\x80\x87",
'PUNCTUATION SPACE' => "\xe2\x80\x88",
'THIN SPACE' => "\xe2\x80\x89",
'HAIR SPACE' => "\xe2\x80\x8a",
'LINE SEPARATOR' => "\xe2\x80\xa8",
'PARAGRAPH SEPARATOR' => "\xe2\x80\xa9",
'ZERO WIDTH SPACE' => "\xe2\x80\x8b",
'NARROW NO-BREAK SPACE' => "\xe2\x80\xaf",
'MEDIUM MATHEMATICAL SPACE' => "\xe2\x81\x9f",
'IDEOGRAPHIC SPACE' => "\xe3\x80\x80",
'HALFWIDTH HANGUL FILLER' => "\xef\xbe\xa0",
];
/**
* @var array{upper: string[], lower: string[]}
*/
private static $COMMON_CASE_FOLD = [
'upper' => [
'µ',
'ſ',
"\xCD\x85",
'ς',
'ẞ',
"\xCF\x90",
"\xCF\x91",
"\xCF\x95",
"\xCF\x96",
"\xCF\xB0",
"\xCF\xB1",
"\xCF\xB5",
"\xE1\xBA\x9B",
"\xE1\xBE\xBE",
],
'lower' => [
'μ',
's',
'ι',
'σ',
'ß',
'β',
'θ',
'φ',
'π',
'κ',
'ρ',
'ε',
"\xE1\xB9\xA1",
'ι',
],
];
/**
* @var array
*/
private static $SUPPORT = [];
/**
* @var array|null
*/
private static $BROKEN_UTF8_FIX;
/**
* @var array|null
*/
private static $WIN1252_TO_UTF8;
/**
* @var array|null
*/
private static $INTL_TRANSLITERATOR_LIST;
/**
* @var array|null
*/
private static $ENCODINGS;
/**
* @var array|null
*/
private static $ORD;
/**
* @var array|null
*/
private static $EMOJI;
/**
* @var array|null
*/
private static $EMOJI_VALUES_CACHE;
/**
* @var array|null
*/
private static $EMOJI_KEYS_CACHE;
/**
* @var array|null
*/
private static $EMOJI_KEYS_REVERSIBLE_CACHE;
/**
* @var array|null
*/
private static $CHR;
/**
* __construct()
*/
public function __construct()
{
}
/**
* Return the character at the specified position: $str[1] like functionality.
*
* @param string $str <p>A UTF-8 string.</p>
* @param int $pos <p>The position of character to return.</p>
* @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
*
* @return string single multi-byte character
*/
public static function access(string $str, int $pos, string $encoding = 'UTF-8'): string
{
if ($str === '' || $pos < 0) {
return '';
}
if ($encoding === 'UTF-8') {
return (string) \mb_substr($str, $pos, 1);
}
return (string) self::substr($str, $pos, 1, $encoding);
}
/**
* Prepends UTF-8 BOM character to the string and returns the whole string.
*
* INFO: If BOM already existed there, the Input string is returned.
*
* @param string $str <p>The input string.</p>
*
* @return string the output string that contains BOM
*/
public static function add_bom_to_string(string $str): string
{
if (self::string_has_bom($str) === false) {
$str = self::bom() . $str;
}
return $str;
}
/**
* Changes all keys in an array.
*
* @param array $array <p>The array to work on</p>
* @param int $case [optional] <p> Either <strong>CASE_UPPER</strong><br>
* or <strong>CASE_LOWER</strong> (default)</p>
* @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
*
* @return string[]
* <p>An array with its keys lower- or uppercased.</p>
*/
public static function array_change_key_case(
array $array,
int $case = \CASE_LOWER,
string $encoding = 'UTF-8'
): array {
if (
$case !== \CASE_LOWER
&&
$case !== \CASE_UPPER
) {
$case = \CASE_LOWER;
}
$return = [];
foreach ($array as $key => &$value) {
$key = $case === \CASE_LOWER
? self::strtolower((string) $key, $encoding)
: self::strtoupper((string) $key, $encoding);
$return[$key] = $value;
}
return $return;
}
/**
* Returns the substring between $start and $end, if found, or an empty
* string. An optional offset may be supplied from which to begin the
* search for the start string.
*
* @param string $str
* @param string $start <p>Delimiter marking the start of the substring.</p>
* @param string $end <p>Delimiter marking the end of the substring.</p>
* @param int $offset [optional] <p>Index from which to begin the search. Default: 0</p>
* @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
*
* @return string
*/
public static function between(
string $str,
string $start,
string $end,
int $offset = 0,
string $encoding = 'UTF-8'
): string {
if ($encoding === 'UTF-8') {
$start_position = \mb_strpos($str, $start, $offset);
if ($start_position === false) {
return '';
}
$substr_index = $start_position + (int) \mb_strlen($start);
$end_position = \mb_strpos($str, $end, $substr_index);
if (
$end_position === false
||
$end_position === $substr_index
) {
return '';
}
return (string) \mb_substr($str, $substr_index, $end_position - $substr_index);
}
$encoding = self::normalize_encoding($encoding, 'UTF-8');
$start_position = self::strpos($str, $start, $offset, $encoding);
if ($start_position === false) {
return '';
}
$substr_index = $start_position + (int) self::strlen($start, $encoding);
$end_position = self::strpos($str, $end, $substr_index, $encoding);
if (
$end_position === false
||
$end_position === $substr_index
) {
return '';
}
return (string) self::substr(
$str,
$substr_index,
$end_position - $substr_index,
$encoding
);
}
/**
* Convert binary into a string.
*
* @param mixed $bin 1|0
*
* @return string
*/
public static function binary_to_str($bin): string
{
if (!isset($bin[0])) {
return '';
}
$convert = \base_convert($bin, 2, 16);
if ($convert === '0') {
return '';
}
return \pack('H*', $convert);
}
/**
* Returns the UTF-8 Byte Order Mark Character.
*
* INFO: take a look at UTF8::$bom for e.g. UTF-16 and UTF-32 BOM values
*
* @return string UTF-8 Byte Order Mark
*/
public static function bom(): string
{
return "\xef\xbb\xbf";
}
/**
* @alias of UTF8::chr_map()
*
* @param callable $callback
* @param string $str
*
* @return string[]
*
* @see UTF8::chr_map()
*/
public static function callback($callback, string $str): array
{
return self::chr_map($callback, $str);
}
/**
* Returns the character at $index, with indexes starting at 0.
*
* @param string $str <p>The input string.</p>
* @param int $index <p>Position of the character.</p>
* @param string $encoding [optional] <p>Default is UTF-8</p>
*
* @return string the character at $index
*/
public static function char_at(string $str, int $index, string $encoding = 'UTF-8'): string
{
if ($encoding === 'UTF-8') {
return (string) \mb_substr($str, $index, 1);
}
return (string) self::substr($str, $index, 1, $encoding);
}
/**
* Returns an array consisting of the characters in the string.
*
* @param string $str <p>The input string.</p>
*
* @return string[] an array of chars
*/
public static function chars(string $str): array
{
return self::str_split($str);
}
/**
* This method will auto-detect your server environment for UTF-8 support.
*
* @return true|null
*
* @internal <p>You don't need to run it manually, it will be triggered if it's needed.</p>
*/
public static function checkForSupport()
{
if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
self::$SUPPORT['already_checked_via_portable_utf8'] = true;
// http://php.net/manual/en/book.mbstring.php
self::$SUPPORT['mbstring'] = self::mbstring_loaded();
self::$SUPPORT['mbstring_func_overload'] = self::mbstring_overloaded();
if (self::$SUPPORT['mbstring'] === true) {
\mb_internal_encoding('UTF-8');
/** @noinspection UnusedFunctionResultInspection */
/** @noinspection PhpComposerExtensionStubsInspection */
\mb_regex_encoding('UTF-8');
self::$SUPPORT['mbstring_internal_encoding'] = 'UTF-8';
}
// http://php.net/manual/en/book.iconv.php
self::$SUPPORT['iconv'] = self::iconv_loaded();
// http://php.net/manual/en/book.intl.php
self::$SUPPORT['intl'] = self::intl_loaded();
// http://php.net/manual/en/class.intlchar.php
self::$SUPPORT['intlChar'] = self::intlChar_loaded();
// http://php.net/manual/en/book.ctype.php
self::$SUPPORT['ctype'] = self::ctype_loaded();
// http://php.net/manual/en/class.finfo.php
self::$SUPPORT['finfo'] = self::finfo_loaded();
// http://php.net/manual/en/book.json.php
self::$SUPPORT['json'] = self::json_loaded();
// http://php.net/manual/en/book.pcre.php
self::$SUPPORT['pcre_utf8'] = self::pcre_utf8_support();
self::$SUPPORT['symfony_polyfill_used'] = self::symfony_polyfill_used();
if (self::$SUPPORT['symfony_polyfill_used'] === true) {
\mb_internal_encoding('UTF-8');
self::$SUPPORT['mbstring_internal_encoding'] = 'UTF-8';
}
return true;
}
return null;
}
/**
* Generates a UTF-8 encoded character from the given code point.
*
* INFO: opposite to UTF8::ord()
*
* @param int|string $code_point <p>The code point for which to generate a character.</p>
* @param string $encoding [optional] <p>Default is UTF-8</p>
*
* @return string|null multi-byte character, returns null on failure or empty input
*/
public static function chr($code_point, string $encoding = 'UTF-8')
{
// init
static $CHAR_CACHE = [];
if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
$encoding = self::normalize_encoding($encoding, 'UTF-8');
}
if (
$encoding !== 'UTF-8'
&&
$encoding !== 'ISO-8859-1'
&&
$encoding !== 'WINDOWS-1252'
&&
self::$SUPPORT['mbstring'] === false
) {
\trigger_error('UTF8::chr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
}
$cache_key = $code_point . $encoding;
if (isset($CHAR_CACHE[$cache_key]) === true) {
return $CHAR_CACHE[$cache_key];
}
if ($code_point <= 127) { // use "simple"-char only until "\x80"
if (self::$CHR === null) {
self::$CHR = self::getData('chr');
}
/**
* @psalm-suppress PossiblyNullArrayAccess
*/
$chr = self::$CHR[$code_point];
if ($encoding !== 'UTF-8') {
$chr = self::encode($encoding, $chr);
}
return $CHAR_CACHE[$cache_key] = $chr;
}
//
// fallback via "IntlChar"
//
if (self::$SUPPORT['intlChar'] === true) {
/** @noinspection PhpComposerExtensionStubsInspection */
$chr = \IntlChar::chr($code_point);
if ($encoding !== 'UTF-8') {
$chr = self::encode($encoding, $chr);
}
return $CHAR_CACHE[$cache_key] = $chr;
}
//
// fallback via vanilla php
//
if (self::$CHR === null) {
self::$CHR = self::getData('chr');
}
$code_point = (int) $code_point;
if ($code_point <= 0x7F) {
/**
* @psalm-suppress PossiblyNullArrayAccess
*/
$chr = self::$CHR[$code_point];
} elseif ($code_point <= 0x7FF) {
/**
* @psalm-suppress PossiblyNullArrayAccess
*/
$chr = self::$CHR[($code_point >> 6) + 0xC0] .
self::$CHR[($code_point & 0x3F) + 0x80];
} elseif ($code_point <= 0xFFFF) {
/**
* @psalm-suppress PossiblyNullArrayAccess
*/
$chr = self::$CHR[($code_point >> 12) + 0xE0] .
self::$CHR[(($code_point >> 6) & 0x3F) + 0x80] .
self::$CHR[($code_point & 0x3F) + 0x80];
} else {
/**
* @psalm-suppress PossiblyNullArrayAccess
*/
$chr = self::$CHR[($code_point >> 18) + 0xF0] .
self::$CHR[(($code_point >> 12) & 0x3F) + 0x80] .
self::$CHR[(($code_point >> 6) & 0x3F) + 0x80] .
self::$CHR[($code_point & 0x3F) + 0x80];
}
if ($encoding !== 'UTF-8') {
$chr = self::encode($encoding, $chr);
}
return $CHAR_CACHE[$cache_key] = $chr;
}
/**
* Applies callback to all characters of a string.
*
* @param callable $callback <p>The callback function.</p>
* @param string $str <p>UTF-8 string to run callback on.</p>
*
* @return string[]
* <p>The outcome of the callback, as array.</p>
*/
public static function chr_map($callback, string $str): array
{
return \array_map(
$callback,
self::str_split($str)
);
}
/**
* Generates an array of byte length of each character of a Unicode string.
*
* 1 byte => U+0000 - U+007F
* 2 byte => U+0080 - U+07FF
* 3 byte => U+0800 - U+FFFF
* 4 byte => U+10000 - U+10FFFF
*
* @param string $str <p>The original unicode string.</p>
*
* @return int[] an array of byte lengths of each character
*/
public static function chr_size_list(string $str): array
{
if ($str === '') {
return [];
}
if (self::$SUPPORT['mbstring_func_overload'] === true) {
return \array_map(
static function (string $data): int {
// "mb_" is available if overload is used, so use it ...
return \mb_strlen($data, 'CP850'); // 8-BIT
},
self::str_split($str)
);
}
return \array_map('\strlen', self::str_split($str));
}
/**
* Get a decimal code representation of a specific character.
*
* @param string $char <p>The input character.</p>
*
* @return int
*/
public static function chr_to_decimal(string $char): int
{
if (self::$SUPPORT['iconv'] === true) {
$chr_tmp = \iconv('UTF-8', 'UCS-4LE', $char);
if ($chr_tmp !== false) {
/** @noinspection OffsetOperationsInspection */
return \unpack('V', $chr_tmp)[1];
}
}
$code = self::ord($char[0]);
$bytes = 1;
if (!($code & 0x80)) {
// 0xxxxxxx
return $code;
}
if (($code & 0xe0) === 0xc0) {
// 110xxxxx
$bytes = 2;
$code &= ~0xc0;
} elseif (($code & 0xf0) === 0xe0) {
// 1110xxxx
$bytes = 3;
$code &= ~0xe0;
} elseif (($code & 0xf8) === 0xf0) {
// 11110xxx
$bytes = 4;
$code &= ~0xf0;
}
for ($i = 2; $i <= $bytes; ++$i) {
// 10xxxxxx
$code = ($code << 6) + (self::ord($char[$i - 1]) & ~0x80);
}
return $code;
}
/**
* Get hexadecimal code point (U+xxxx) of a UTF-8 encoded character.
*
* @param int|string $char <p>The input character</p>
* @param string $prefix [optional]
*
* @return string The code point encoded as U+xxxx
*/
public static function chr_to_hex($char, string $prefix = 'U+'): string
{
if ($char === '') {
return '';
}
if ($char === '�') {
$char = '';
}
return self::int_to_hex(self::ord((string) $char), $prefix);
}
/**
* alias for "UTF8::chr_to_decimal()"
*
* @param string $chr
*
* @return int
*
* @see UTF8::chr_to_decimal()
* @deprecated <p>please use "UTF8::chr_to_decimal()"</p>
*/
public static function chr_to_int(string $chr): int
{
return self::chr_to_decimal($chr);
}
/**
* Splits a string into smaller chunks and multiple lines, using the specified line ending character.
*
* @param string $body <p>The original string to be split.</p>
* @param int $chunk_length [optional] <p>The maximum character length of a chunk.</p>
* @param string $end [optional] <p>The character(s) to be inserted at the end of each chunk.</p>
*
* @return string the chunked string
*/
public static function chunk_split(string $body, int $chunk_length = 76, string $end = "\r\n"): string
{
return \implode($end, self::str_split($body, $chunk_length));
}
/**
* Accepts a string and removes all non-UTF-8 characters from it + extras if needed.
*
* @param string $str <p>The string to be sanitized.</p>
* @param bool $remove_bom [optional] <p>Set to true, if you need to remove UTF-BOM.</p>
* @param bool $normalize_whitespace [optional] <p>Set to true, if you need to normalize the
* whitespace.</p>
* @param bool $normalize_msword [optional] <p>Set to true, if you need to normalize MS Word chars
* e.g.: "…"
* => "..."</p>
* @param bool $keep_non_breaking_space [optional] <p>Set to true, to keep non-breaking-spaces, in
* combination with
* $normalize_whitespace</p>
* @param bool $replace_diamond_question_mark [optional] <p>Set to true, if you need to remove diamond question
* mark e.g.: "�"</p>
* @param bool $remove_invisible_characters [optional] <p>Set to false, if you not want to remove invisible
* characters e.g.: "\0"</p>
* @param bool $remove_invisible_characters_url_encoded [optional] <p>Set to true, if you not want to remove invisible
* url encoded characters e.g.: "%0B"<br>
* WARNING: maybe contains false-positives e.g. aa%0Baa -> aaaa.
* </p>
*
* @return string clean UTF-8 encoded string
*/
public static function clean(
string $str,
bool $remove_bom = false,
bool $normalize_whitespace = false,
bool $normalize_msword = false,
bool $keep_non_breaking_space = false,
bool $replace_diamond_question_mark = false,
bool $remove_invisible_characters = true,
bool $remove_invisible_characters_url_encoded = false
): string {
// http://stackoverflow.com/questions/1401317/remove-non-utf8-characters-from-string
// caused connection reset problem on larger strings
$regex = '/
(
(?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
| [\xC0-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
| [\xE0-\xEF][\x80-\xBF]{2} # triple-byte sequences 1110xxxx 10xxxxxx * 2
| [\xF0-\xF7][\x80-\xBF]{3} # quadruple-byte sequence 11110xxx 10xxxxxx * 3
){1,100} # ...one or more times
)
| ( [\x80-\xBF] ) # invalid byte in range 10000000 - 10111111
| ( [\xC0-\xFF] ) # invalid byte in range 11000000 - 11111111
/x';
/** @noinspection NotOptimalRegularExpressionsInspection */
$str = (string) \preg_replace($regex, '$1', $str);
if ($replace_diamond_question_mark === true) {
$str = self::replace_diamond_question_mark($str, '');
}
if ($remove_invisible_characters === true) {
$str = self::remove_invisible_characters($str, $remove_invisible_characters_url_encoded);
}
if ($normalize_whitespace === true) {
$str = self::normalize_whitespace($str, $keep_non_breaking_space);
}
if ($normalize_msword === true) {
$str = self::normalize_msword($str);
}
if ($remove_bom === true) {
$str = self::remove_bom($str);
}
return $str;
}
/**
* Clean-up a string and show only printable UTF-8 chars at the end + fix UTF-8 encoding.
*
* @param string $str <p>The input string.</p>
*
* @return string
*/
public static function cleanup($str): string
{
// init
$str = (string) $str;
if ($str === '') {
return '';
}
// fixed ISO <-> UTF-8 Errors
$str = self::fix_simple_utf8($str);
// remove all none UTF-8 symbols
// && remove diamond question mark (�)
// && remove remove invisible characters (e.g. "\0")
// && remove BOM
// && normalize whitespace chars (but keep non-breaking-spaces)
return self::clean(
$str,
true,
true,
false,
true,
true,
true
);
}
/**
* Accepts a string or a array of strings and returns an array of Unicode code points.
*
* INFO: opposite to UTF8::string()
*
* @param string|string[] $arg <p>A UTF-8 encoded string or an array of such strings.</p>
* @param bool $u_style <p>If True, will return code points in U+xxxx format,
* default, code points will be returned as integers.</p>
*
* @return array<int|string>
* The array of code points:<br>
* array<int> for $u_style === false<br>
* array<string> for $u_style === true<br>
*/
public static function codepoints($arg, bool $u_style = false): array
{
if (\is_string($arg) === true) {
$arg = self::str_split($arg);
}
/**
* @psalm-suppress DocblockTypeContradiction
*/
if (!\is_array($arg)) {
return [];
}
if ($arg === []) {
return [];
}
$arg = \array_map(
[
self::class,
'ord',
],
$arg
);
if ($u_style === true) {
$arg = \array_map(
[
self::class,
'int_to_hex',
],
$arg
);
}
return $arg;
}
/**
* Trims the string and replaces consecutive whitespace characters with a
* single space. This includes tabs and newline characters, as well as
* multibyte whitespace such as the thin space and ideographic space.
*
* @param string $str <p>The input string.</p>
*
* @return string string with a trimmed $str and condensed whitespace
*/
public static function collapse_whitespace(string $str): string
{
if (self::$SUPPORT['mbstring'] === true) {
/** @noinspection PhpComposerExtensionStubsInspection */
return \trim((string) \mb_ereg_replace('[[:space:]]+', ' ', $str));
}
return \trim(self::regex_replace($str, '[[:space:]]+', ' '));
}
/**
* Returns count of characters used in a string.
*
* @param string $str <p>The input string.</p>
* @param bool $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
* @param bool $try_to_use_mb_functions [optional] <p>Set to false, if you don't want to use
*
* @return int[] an associative array of Character as keys and
* their count as values
*/
public static function count_chars(
string $str,
bool $clean_utf8 = false,
bool $try_to_use_mb_functions = true
): array {
return \array_count_values(
self::str_split(
$str,
1,
$clean_utf8,
$try_to_use_mb_functions
)
);
}
/**
* Remove css media-queries.
*
* @param string $str
*
* @return string
*/
public static function css_stripe_media_queries(string $str): string
{
return (string) \preg_replace(
'#@media\\s+(?:only\\s)?(?:[\\s{(]|screen|all)\\s?[^{]+{.*}\\s*}\\s*#isumU',
'',
$str
);
}
/**
* Checks whether ctype is available on the server.
*
* @return bool
* <strong>true</strong> if available, <strong>false</strong> otherwise
*/
public static function ctype_loaded(): bool
{
return \extension_loaded('ctype');
}
/**
* Converts an int value into a UTF-8 character.
*
* @param mixed $int
*
* @return string
*/
public static function decimal_to_chr($int): string
{
return self::html_entity_decode('&#' . $int . ';', \ENT_QUOTES | \ENT_HTML5);
}
/**