Passed
Push — master ( 0f9f15...4a5f22 )
by Lars
05:30
created

UTF8   F

Complexity

Total Complexity 1782

Size/Duplication

Total Lines 14807
Duplicated Lines 0 %

Test Coverage

Coverage 80.44%

Importance

Changes 107
Bugs 53 Features 6
Metric Value
eloc 4536
c 107
b 53
f 6
dl 0
loc 14807
ccs 3063
cts 3808
cp 0.8044
rs 0.8
wmc 1782

310 Methods

Rating   Name   Duplication   Size   Complexity  
A add_bom_to_string() 0 7 2
A array_change_key_case() 0 23 5
A __construct() 0 2 1
B between() 0 48 8
A char_at() 0 7 2
A chars() 0 4 1
A access() 0 11 4
A callback() 0 3 1
A binary_to_str() 0 12 3
A bom() 0 3 1
B chr_to_decimal() 0 38 8
A file_has_bom() 0 8 2
A filter_input() 0 16 3
A get_unique_string() 0 22 3
A is_bom() 0 10 3
A is_hexadecimal() 0 8 2
A encode_mimeheader() 0 26 5
A count_chars() 0 11 1
A ctype_loaded() 0 3 1
A has_uppercase() 0 8 2
A isBinary() 0 3 1
A emoji_decode() 0 18 2
A is_utf8() 0 13 4
A lcword() 0 13 1
D chr() 0 109 19
A html_escape() 0 6 1
B get_file_type() 0 65 7
A chr_to_int() 0 3 1
C is_utf16() 0 71 16
A isHtml() 0 3 1
C filter() 0 57 12
A isBase64() 0 3 1
A is_html() 0 14 2
A decode_mimeheader() 0 8 3
A html_decode() 0 6 1
A isUtf32() 0 3 1
A chunk_split() 0 3 1
A emoji_encode() 0 18 2
A is_alpha() 0 8 2
B get_random_string() 0 56 10
A fix_utf8() 0 30 4
A first_char() 0 14 4
A css_identifier() 0 56 6
A isUtf8() 0 3 1
A css_stripe_media_queries() 0 6 1
A clean() 0 48 6
A is_serialized() 0 11 3
A is_uppercase() 0 8 2
A is_ascii() 0 3 1
A is_blank() 0 8 2
D getCharDirection() 0 105 118
A htmlspecialchars() 0 15 3
A filter_var_array() 0 15 2
A decimal_to_chr() 0 3 1
A has_whitespace() 0 8 2
A codepoints() 0 36 5
A lowerCaseFirst() 0 13 1
A chr_map() 0 5 1
A cleanup() 0 24 2
B is_binary() 0 38 9
A intlChar_loaded() 0 3 1
A lcfirst() 0 44 5
B is_url() 0 44 7
A finfo_loaded() 0 3 1
A fits_inside() 0 3 1
A is_binary_file() 0 16 4
A intl_loaded() 0 3 1
A html_stripe_empty_tags() 0 6 1
F extract_text() 0 175 34
A json_loaded() 0 3 1
A isBom() 0 3 1
A int_to_chr() 0 3 1
A is_lowercase() 0 8 2
A hasBom() 0 3 1
A iconv_loaded() 0 3 1
A lcwords() 0 34 6
A isAscii() 0 3 1
A filter_var() 0 15 2
A is_empty() 0 3 1
A isUtf16() 0 3 1
F encode() 0 147 37
C is_utf32() 0 71 16
A is_alphanumeric() 0 8 2
A json_decode() 0 14 2
A fix_simple_utf8() 0 32 4
A checkForSupport() 0 48 4
A is_printable() 0 3 1
B is_json() 0 27 8
A int_to_hex() 0 7 2
A has_lowercase() 0 8 2
A json_encode() 0 10 2
A is_base64() 0 17 5
A hex_to_int() 0 14 3
A htmlentities() 0 28 3
A hex_to_chr() 0 4 1
A isJson() 0 3 1
A filter_input_array() 0 15 3
A getSupportInfo() 0 13 3
A chr_to_hex() 0 11 3
A is_punctuation() 0 3 1
A collapse_whitespace() 0 8 2
C html_entity_decode() 0 59 13
B file_get_contents() 0 56 11
A emoji_from_country_code() 0 17 3
A mbstring_overloaded() 0 11 2
A str_substr_after_first_separator() 0 28 6
A str_begins() 0 3 1
A max() 0 14 3
B str_camelize() 0 74 10
A parse_str() 0 18 4
A str_contains() 0 15 3
B str_to_lines() 0 29 8
A substr_in_byte() 0 18 6
A stripos_in_byte() 0 12 4
A strnatcasecmp() 0 5 1
A substr_left() 0 15 4
D strlen() 0 104 19
A str_isubstr_last() 0 25 4
A to_int() 0 7 2
A str_replace_beginning() 0 25 6
A remove_left() 0 28 4
C stripos() 0 67 14
A str_offset_exists() 0 10 2
D strrchr() 0 104 20
A to_filename() 0 9 1
A str_iends_with() 0 11 3
A max_chr_width() 0 8 2
C utf8_decode() 0 61 13
A ltrim() 0 27 5
A remove_html() 0 3 1
B str_longest_common_suffix() 0 54 10
C wordwrap() 0 72 15
B ucfirst() 0 57 7
A str_pad_both() 0 12 1
A str_index_last() 0 11 1
A str_substr_last() 0 33 6
A mbstring_loaded() 0 3 1
A str_limit() 0 26 6
A toUTF8() 0 3 1
B str_obfuscate() 0 47 8
A string() 0 16 4
D normalize_encoding() 0 147 16
B rxClass() 0 45 8
A str_ensure_right() 0 13 4
B str_titleize_for_humans() 0 171 7
A normalize_whitespace() 0 9 1
A str_starts_with() 0 16 4
A str_humanize() 0 15 1
C substr_count_in_byte() 0 55 15
A strchr() 0 13 1
A strichr() 0 13 1
A str_index_first() 0 11 1
A strlen_in_byte() 0 12 3
A str_ireplace_ending() 0 21 6
A rtrim() 0 27 5
C str_longest_common_substring() 0 76 16
A regex_replace() 0 20 3
A titlecase() 0 35 5
A getData() 0 6 1
A str_iindex_first() 0 11 1
B strtolower() 0 60 10
B urldecode() 0 51 8
A str_isubstr_before_first_separator() 0 19 5
B strrev() 0 43 10
A replace_all() 0 11 2
D substr_replace() 0 124 27
A removeBOM() 0 3 1
A strstr_in_byte() 0 15 4
A str_matches_pattern() 0 3 1
C str_titleize() 0 69 12
A str_split_array() 0 17 2
A ws() 0 3 1
A str_replace_first() 0 20 2
A toLatin1() 0 3 1
A str_pad_right() 0 12 1
B ucwords() 0 51 9
A to_boolean() 0 35 5
C stristr() 0 79 17
A strncasecmp() 0 10 1
B strwidth() 0 43 8
A str_iends() 0 3 1
A trim() 0 27 5
A str_upper_camelize() 0 8 1
A substr_compare() 0 33 6
D substr_count() 0 73 17
A strnatcmp() 0 9 2
D str_pad() 0 146 16
A urldecode_unicode_helper() 0 8 2
A str_ireplace() 0 31 5
A to_latin1() 0 3 1
A str_replace_ending() 0 24 6
A string_has_bom() 0 10 3
B strtr() 0 42 11
B str_contains_all() 0 24 9
A normalize_line_ending() 0 3 1
A str_isubstr_after_last_separator() 0 26 5
D range() 0 72 23
B strspn() 0 30 10
A strcasecmp() 0 21 1
A str_transliterate() 0 6 1
B rawurldecode() 0 51 8
A str_ends() 0 3 1
B str_capitalize_name_helper() 0 86 10
A utf8_encode() 0 16 3
A normalize_msword() 0 3 1
C str_detect_encoding() 0 111 13
A spaces_to_tabs() 0 11 3
A str_istarts_with() 0 11 3
A str_replace() 0 18 1
A substr_iright() 0 15 4
A replace() 0 11 2
A to_iso8859() 0 16 4
A words_limit() 0 20 5
A strip_tags() 0 18 4
A pcre_utf8_support() 0 4 1
A str_isubstr_before_last_separator() 0 24 6
D str_truncate_safe() 0 86 18
A substr_right() 0 31 6
D str_split() 0 138 29
A str_ends_with_any() 0 13 4
A strrpos_in_byte() 0 12 4
A remove_right() 0 25 4
F strrpos() 0 136 31
A remove_html_breaks() 0 3 1
A showSupport() 0 17 3
A remove_invisible_characters() 0 9 1
A single_chr_html_encode() 0 18 4
A str_replace_last() 0 19 2
A str_iindex_last() 0 11 1
A str_substr_before_last_separator() 0 31 6
B strtocasefold() 0 33 7
A tabs_to_spaces() 0 11 3
B str_truncate() 0 44 7
F strripos() 0 113 25
A strpos_in_byte() 0 12 4
A str_ends_with() 0 16 4
A to_ascii() 0 6 1
A reduce_string_array() 0 29 6
B str_longest_common_prefix() 0 51 8
A str_pad_left() 0 12 1
A str_substr_first() 0 33 6
A chr_size_list() 0 17 3
A remove_bom() 0 22 5
A str_repeat() 0 5 1
A strpbrk() 0 11 4
D to_utf8_string() 0 110 33
A whitespace_table() 0 3 1
A substr_count_simple() 0 31 6
A str_iends_with_any() 0 13 4
A str_substr_after_last_separator() 0 31 6
A str_isubstr_after_first_separator() 0 26 5
B str_snakeize() 0 57 6
A str_sort() 0 15 3
A to_utf8() 0 14 3
A ucword() 0 6 1
A str_underscored() 0 3 1
A str_offset_get() 0 14 4
A strip_whitespace() 0 7 2
A toAscii() 0 6 1
A str_ibegins() 0 3 1
A str_capitalize_name() 0 8 1
B str_limit_after_word() 0 53 11
A str_upper_first() 0 13 1
A normalizeEncoding() 0 3 1
A swapCase() 0 17 4
A substr_ileft() 0 15 4
B html_encode() 0 54 11
A str_dasherize() 0 3 1
A str_ensure_left() 0 11 3
B urldecode_fix_win1252_chars() 0 227 1
A toIso8859() 0 3 1
C ord() 0 77 16
B to_string() 0 33 8
A strtonatfold() 0 13 2
C strcspn() 0 49 12
A fixStrCaseHelper() 0 41 5
B str_split_pattern() 0 49 11
D strstr() 0 107 21
A str_isubstr_first() 0 25 4
A str_last_char() 0 16 4
A str_ireplace_beginning() 0 22 6
A str_substr_before_first_separator() 0 32 6
F substr() 0 138 31
A wordwrap_per_line() 0 28 5
A str_surround() 0 3 1
A strncmp() 0 19 4
A str_insert() 0 28 4
A utf8_fix_win1252_chars() 0 3 1
A replace_diamond_question_mark() 0 43 5
D is_utf8_string() 0 134 28
A to_utf8_convert_helper() 0 28 5
B str_delimit() 0 33 8
B strtoupper() 0 60 10
A min() 0 14 3
A str_starts_with_any() 0 17 5
B strrichr() 0 54 11
A split() 0 7 1
A str_istarts_with_any() 0 17 5
B str_contains_any() 0 29 8
A initEmojiData() 0 29 4
A remove_duplicates() 0 16 4
B str_slice() 0 33 10
F strpos() 0 151 33
A str_shuffle() 0 35 6
A strcmp() 0 9 2
A str_word_count() 0 23 5
A strripos_in_byte() 0 12 4
A str_to_binary() 0 10 2
A symfony_polyfill_used() 0 16 5
B str_to_words() 0 36 8

How to fix   Complexity   

Complex Class

Complex classes like UTF8 often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use UTF8, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace voku\helper;
6
7
/**
8
 * @psalm-immutable
9
 */
10
final class UTF8
11
{
12
    /**
13
     * (CRLF|([ZWNJ-ZWJ]|T+|L*(LV?V+|LV|LVT)T*|L+|[^Control])[Extend]*|[Control])
14
     * This regular expression is a work around for http://bugs.exim.org/1279
15
     *
16
     * @deprecated <p>please don't use it anymore</p>
17
     */
18
    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}])";
19
20
    /**
21
     * Bom => Byte-Length
22
     *
23
     * INFO: https://en.wikipedia.org/wiki/Byte_order_mark
24
     *
25
     * @var array<string, int>
26
     */
27
    private static $BOM = [
28
        "\xef\xbb\xbf"     => 3, // UTF-8 BOM
29
        ''              => 6, // UTF-8 BOM as "WINDOWS-1252" (one char has [maybe] more then one byte ...)
30
        "\x00\x00\xfe\xff" => 4, // UTF-32 (BE) BOM
31
        '  þÿ'             => 6, // UTF-32 (BE) BOM as "WINDOWS-1252"
32
        "\xff\xfe\x00\x00" => 4, // UTF-32 (LE) BOM
33
        'ÿþ  '             => 6, // UTF-32 (LE) BOM as "WINDOWS-1252"
34
        "\xfe\xff"         => 2, // UTF-16 (BE) BOM
35
        'þÿ'               => 4, // UTF-16 (BE) BOM as "WINDOWS-1252"
36
        "\xff\xfe"         => 2, // UTF-16 (LE) BOM
37
        'ÿþ'               => 4, // UTF-16 (LE) BOM as "WINDOWS-1252"
38
    ];
39
40
    /**
41
     * Numeric code point => UTF-8 Character
42
     *
43
     * url: http://www.w3schools.com/charsets/ref_utf_punctuation.asp
44
     *
45
     * @var array<int, string>
46
     */
47
    private static $WHITESPACE = [
48
        // NULL Byte
49
        0 => "\x0",
50
        // Tab
51
        9 => "\x9",
52
        // New Line
53
        10 => "\xa",
54
        // Vertical Tab
55
        11 => "\xb",
56
        // Carriage Return
57
        13 => "\xd",
58
        // Ordinary Space
59
        32 => "\x20",
60
        // NO-BREAK SPACE
61
        160 => "\xc2\xa0",
62
        // OGHAM SPACE MARK
63
        5760 => "\xe1\x9a\x80",
64
        // MONGOLIAN VOWEL SEPARATOR
65
        6158 => "\xe1\xa0\x8e",
66
        // EN QUAD
67
        8192 => "\xe2\x80\x80",
68
        // EM QUAD
69
        8193 => "\xe2\x80\x81",
70
        // EN SPACE
71
        8194 => "\xe2\x80\x82",
72
        // EM SPACE
73
        8195 => "\xe2\x80\x83",
74
        // THREE-PER-EM SPACE
75
        8196 => "\xe2\x80\x84",
76
        // FOUR-PER-EM SPACE
77
        8197 => "\xe2\x80\x85",
78
        // SIX-PER-EM SPACE
79
        8198 => "\xe2\x80\x86",
80
        // FIGURE SPACE
81
        8199 => "\xe2\x80\x87",
82
        // PUNCTUATION SPACE
83
        8200 => "\xe2\x80\x88",
84
        // THIN SPACE
85
        8201 => "\xe2\x80\x89",
86
        // HAIR SPACE
87
        8202 => "\xe2\x80\x8a",
88
        // LINE SEPARATOR
89
        8232 => "\xe2\x80\xa8",
90
        // PARAGRAPH SEPARATOR
91
        8233 => "\xe2\x80\xa9",
92
        // NARROW NO-BREAK SPACE
93
        8239 => "\xe2\x80\xaf",
94
        // MEDIUM MATHEMATICAL SPACE
95
        8287 => "\xe2\x81\x9f",
96
        // HALFWIDTH HANGUL FILLER
97
        65440 => "\xef\xbe\xa0",
98
        // IDEOGRAPHIC SPACE
99
        12288 => "\xe3\x80\x80",
100
    ];
101
102
    /**
103
     * @var array<string, string>
104
     */
105
    private static $WHITESPACE_TABLE = [
106
        'SPACE'                     => "\x20",
107
        'NO-BREAK SPACE'            => "\xc2\xa0",
108
        'OGHAM SPACE MARK'          => "\xe1\x9a\x80",
109
        'EN QUAD'                   => "\xe2\x80\x80",
110
        'EM QUAD'                   => "\xe2\x80\x81",
111
        'EN SPACE'                  => "\xe2\x80\x82",
112
        'EM SPACE'                  => "\xe2\x80\x83",
113
        'THREE-PER-EM SPACE'        => "\xe2\x80\x84",
114
        'FOUR-PER-EM SPACE'         => "\xe2\x80\x85",
115
        'SIX-PER-EM SPACE'          => "\xe2\x80\x86",
116
        'FIGURE SPACE'              => "\xe2\x80\x87",
117
        'PUNCTUATION SPACE'         => "\xe2\x80\x88",
118
        'THIN SPACE'                => "\xe2\x80\x89",
119
        'HAIR SPACE'                => "\xe2\x80\x8a",
120
        'LINE SEPARATOR'            => "\xe2\x80\xa8",
121
        'PARAGRAPH SEPARATOR'       => "\xe2\x80\xa9",
122
        'ZERO WIDTH SPACE'          => "\xe2\x80\x8b",
123
        'NARROW NO-BREAK SPACE'     => "\xe2\x80\xaf",
124
        'MEDIUM MATHEMATICAL SPACE' => "\xe2\x81\x9f",
125
        'IDEOGRAPHIC SPACE'         => "\xe3\x80\x80",
126
        'HALFWIDTH HANGUL FILLER'   => "\xef\xbe\xa0",
127
    ];
128
129
    /**
130
     * @var array
131
     *
132
     * @phpstan-var array{upper: string[], lower: string[]}
133
     */
134
    private static $COMMON_CASE_FOLD = [
135
        'upper' => [
136
            'µ',
137
            'ſ',
138
            "\xCD\x85",
139
            'ς',
140
            'ẞ',
141
            "\xCF\x90",
142
            "\xCF\x91",
143
            "\xCF\x95",
144
            "\xCF\x96",
145
            "\xCF\xB0",
146
            "\xCF\xB1",
147
            "\xCF\xB5",
148
            "\xE1\xBA\x9B",
149
            "\xE1\xBE\xBE",
150
        ],
151
        'lower' => [
152
            'μ',
153
            's',
154
            'ι',
155
            'σ',
156
            'ß',
157
            'β',
158
            'θ',
159
            'φ',
160
            'π',
161
            'κ',
162
            'ρ',
163
            'ε',
164
            "\xE1\xB9\xA1",
165
            'ι',
166
        ],
167
    ];
168
169
    /**
170
     * @var array
171
     *
172
     * @phpstan-var array<string, mixed>
173
     */
174
    private static $SUPPORT = [];
175
176
    /**
177
     * @var string[]|null
178
     *
179
     * @phpstan-var array<string, string>|null
180
     */
181
    private static $BROKEN_UTF8_FIX;
182
183
    /**
184
     * @var string[]|null
185
     *
186
     * @phpstan-var array<int, string>|null
187
     */
188
    private static $WIN1252_TO_UTF8;
189
190
    /**
191
     * @var string[]|null
192
     *
193
     * @phpstan-var array<int ,string>|null
194
     */
195
    private static $INTL_TRANSLITERATOR_LIST;
196
197
    /**
198
     * @var string[]|null
199
     *
200
     * @phpstan-var array<string>|null
201
     */
202
    private static $ENCODINGS;
203
204
    /**
205
     * @var int[]|null
206
     *
207
     * @phpstan-var array<string ,int>|null
208
     */
209
    private static $ORD;
210
211
    /**
212
     * @var string[]|null
213
     *
214
     * @phpstan-var array<string, string>|null
215
     */
216
    private static $EMOJI;
217
218
    /**
219
     * @var string[]|null
220
     *
221
     * @phpstan-var array<string>|null
222
     */
223
    private static $EMOJI_VALUES_CACHE;
224
225
    /**
226
     * @var string[]|null
227
     *
228
     * @phpstan-var array<string>|null
229
     */
230
    private static $EMOJI_KEYS_CACHE;
231
232
    /**
233
     * @var string[]|null
234
     *
235
     * @phpstan-var array<string>|null
236
     */
237
    private static $EMOJI_KEYS_REVERSIBLE_CACHE;
238
239
    /**
240
     * @var string[]|null
241
     *
242
     * @phpstan-var array<int, string>|null
243
     */
244
    private static $CHR;
245
246
    /**
247
     * __construct()
248
     */
249 34
    public function __construct()
250
    {
251 34
    }
252
253
    /**
254
     * Return the character at the specified position: $str[1] like functionality.
255
     *
256
     * EXAMPLE: <code>UTF8::access('fòô', 1); // 'ò'</code>
257
     *
258
     * @param string $str      <p>A UTF-8 string.</p>
259
     * @param int    $pos      <p>The position of character to return.</p>
260
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
261
     *
262
     * @psalm-pure
263
     *
264
     * @return string
265
     *                <p>Single multi-byte character.</p>
266
     */
267 3
    public static function access(string $str, int $pos, string $encoding = 'UTF-8'): string
268
    {
269 3
        if ($str === '' || $pos < 0) {
270 2
            return '';
271
        }
272
273 3
        if ($encoding === 'UTF-8') {
274 3
            return (string) \mb_substr($str, $pos, 1);
275
        }
276
277
        return (string) self::substr($str, $pos, 1, $encoding);
278
    }
279
280
    /**
281
     * Prepends UTF-8 BOM character to the string and returns the whole string.
282
     *
283
     * INFO: If BOM already existed there, the Input string is returned.
284
     *
285
     * EXAMPLE: <code>UTF8::add_bom_to_string('fòô'); // "\xEF\xBB\xBF" . 'fòô'</code>
286
     *
287
     * @param string $str <p>The input string.</p>
288
     *
289
     * @psalm-pure
290
     *
291
     * @return string
292
     *                <p>The output string that contains BOM.</p>
293
     */
294 2
    public static function add_bom_to_string(string $str): string
295
    {
296 2
        if (!self::string_has_bom($str)) {
297 2
            $str = self::bom() . $str;
298
        }
299
300 2
        return $str;
301
    }
302
303
    /**
304
     * Changes all keys in an array.
305
     *
306
     * @param array<string, mixed> $array    <p>The array to work on</p>
307
     * @param int                  $case     [optional] <p> Either <strong>CASE_UPPER</strong><br>
308
     *                                       or <strong>CASE_LOWER</strong> (default)</p>
309
     * @param string               $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
310
     *
311
     * @psalm-pure
312
     *
313
     * @return string[]
314
     *                  <p>An array with its keys lower- or uppercased.</p>
315
     */
316 2
    public static function array_change_key_case(
317
        array $array,
318
        int $case = \CASE_LOWER,
319
        string $encoding = 'UTF-8'
320
    ): array {
321
        if (
322 2
            $case !== \CASE_LOWER
323
            &&
324 2
            $case !== \CASE_UPPER
325
        ) {
326
            $case = \CASE_LOWER;
327
        }
328
329 2
        $return = [];
330 2
        foreach ($array as $key => &$value) {
331 2
            $key = $case === \CASE_LOWER
332 2
                ? self::strtolower((string) $key, $encoding)
333 2
                : self::strtoupper((string) $key, $encoding);
334
335 2
            $return[$key] = $value;
336
        }
337
338 2
        return $return;
339
    }
340
341
    /**
342
     * Returns the substring between $start and $end, if found, or an empty
343
     * string. An optional offset may be supplied from which to begin the
344
     * search for the start string.
345
     *
346
     * @param string $str
347
     * @param string $start    <p>Delimiter marking the start of the substring.</p>
348
     * @param string $end      <p>Delimiter marking the end of the substring.</p>
349
     * @param int    $offset   [optional] <p>Index from which to begin the search. Default: 0</p>
350
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
351
     *
352
     * @psalm-pure
353
     *
354
     * @return string
355
     */
356 16
    public static function between(
357
        string $str,
358
        string $start,
359
        string $end,
360
        int $offset = 0,
361
        string $encoding = 'UTF-8'
362
    ): string {
363 16
        if ($encoding === 'UTF-8') {
364 8
            $start_position = \mb_strpos($str, $start, $offset);
365 8
            if ($start_position === false) {
366 1
                return '';
367
            }
368
369 7
            $substr_index = $start_position + (int) \mb_strlen($start);
370 7
            $end_position = \mb_strpos($str, $end, $substr_index);
371
            if (
372 7
                $end_position === false
373
                ||
374 7
                $end_position === $substr_index
375
            ) {
376 2
                return '';
377
            }
378
379 5
            return (string) \mb_substr($str, $substr_index, $end_position - $substr_index);
380
        }
381
382 8
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
383
384 8
        $start_position = self::strpos($str, $start, $offset, $encoding);
385 8
        if ($start_position === false) {
386 1
            return '';
387
        }
388
389 7
        $substr_index = $start_position + (int) self::strlen($start, $encoding);
390 7
        $end_position = self::strpos($str, $end, $substr_index, $encoding);
391
        if (
392 7
            $end_position === false
393
            ||
394 7
            $end_position === $substr_index
395
        ) {
396 2
            return '';
397
        }
398
399 5
        return (string) self::substr(
400 5
            $str,
401 5
            $substr_index,
402 5
            $end_position - $substr_index,
403 5
            $encoding
404
        );
405
    }
406
407
    /**
408
     * Convert binary into a string.
409
     *
410
     * INFO: opposite to UTF8::str_to_binary()
411
     *
412
     * EXAMPLE: <code>UTF8::binary_to_str('11110000100111111001100010000011'); // '😃'</code>
413
     *
414
     * @param string $bin 1|0
415
     *
416
     * @psalm-pure
417
     *
418
     * @return string
419
     */
420 2
    public static function binary_to_str($bin): string
421
    {
422 2
        if (!isset($bin[0])) {
423
            return '';
424
        }
425
426 2
        $convert = \base_convert($bin, 2, 16);
427 2
        if ($convert === '0') {
428 1
            return '';
429
        }
430
431 2
        return \pack('H*', $convert);
432
    }
433
434
    /**
435
     * Returns the UTF-8 Byte Order Mark Character.
436
     *
437
     * INFO: take a look at UTF8::$bom for e.g. UTF-16 and UTF-32 BOM values
438
     *
439
     * EXAMPLE: <code>UTF8::bom(); // "\xEF\xBB\xBF"</code>
440
     *
441
     * @psalm-pure
442
     *
443
     * @return string
444
     *                <p>UTF-8 Byte Order Mark.</p>
445
     */
446 4
    public static function bom(): string
447
    {
448 4
        return "\xef\xbb\xbf";
449
    }
450
451
    /**
452
     * @alias of UTF8::chr_map()
453
     *
454
     * @param callable $callback
455
     * @param string   $str
456
     *
457
     * @psalm-pure
458
     *
459
     * @return string[]
460
     *
461
     * @see   UTF8::chr_map()
462
     */
463 2
    public static function callback($callback, string $str): array
464
    {
465 2
        return self::chr_map($callback, $str);
466
    }
467
468
    /**
469
     * Returns the character at $index, with indexes starting at 0.
470
     *
471
     * @param string $str      <p>The input string.</p>
472
     * @param int    $index    <p>Position of the character.</p>
473
     * @param string $encoding [optional] <p>Default is UTF-8</p>
474
     *
475
     * @psalm-pure
476
     *
477
     * @return string
478
     *                <p>The character at $index.</p>
479
     */
480 9
    public static function char_at(string $str, int $index, string $encoding = 'UTF-8'): string
481
    {
482 9
        if ($encoding === 'UTF-8') {
483 5
            return (string) \mb_substr($str, $index, 1);
484
        }
485
486 4
        return (string) self::substr($str, $index, 1, $encoding);
487
    }
488
489
    /**
490
     * Returns an array consisting of the characters in the string.
491
     *
492
     * @param string $str <p>The input string.</p>
493
     *
494
     * @psalm-pure
495
     *
496
     * @return string[]
497
     *                  <p>An array of chars.</p>
498
     */
499 4
    public static function chars(string $str): array
500
    {
501
        /** @var string[] */
502 4
        return self::str_split($str);
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::str_split($str) returns an array which contains values of type array|string[] which are incompatible with the documented value type string.
Loading history...
503
    }
504
505
    /**
506
     * This method will auto-detect your server environment for UTF-8 support.
507
     *
508
     * @return true|null
509
     *
510
     * @internal <p>You don't need to run it manually, it will be triggered if it's needed.</p>
511
     */
512 5
    public static function checkForSupport()
513
    {
514 5
        if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
515
            self::$SUPPORT['already_checked_via_portable_utf8'] = true;
516
517
            // http://php.net/manual/en/book.mbstring.php
518
            self::$SUPPORT['mbstring'] = self::mbstring_loaded();
519
520
            self::$SUPPORT['mbstring_func_overload'] = self::mbstring_overloaded();
521
            if (self::$SUPPORT['mbstring'] === true) {
522
                \mb_internal_encoding('UTF-8');
523
                /** @noinspection UnusedFunctionResultInspection */
524
                /** @noinspection PhpComposerExtensionStubsInspection */
525
                \mb_regex_encoding('UTF-8');
526
                self::$SUPPORT['mbstring_internal_encoding'] = 'UTF-8';
527
            }
528
529
            // http://php.net/manual/en/book.iconv.php
530
            self::$SUPPORT['iconv'] = self::iconv_loaded();
531
532
            // http://php.net/manual/en/book.intl.php
533
            self::$SUPPORT['intl'] = self::intl_loaded();
534
535
            // http://php.net/manual/en/class.intlchar.php
536
            self::$SUPPORT['intlChar'] = self::intlChar_loaded();
537
538
            // http://php.net/manual/en/book.ctype.php
539
            self::$SUPPORT['ctype'] = self::ctype_loaded();
540
541
            // http://php.net/manual/en/class.finfo.php
542
            self::$SUPPORT['finfo'] = self::finfo_loaded();
543
544
            // http://php.net/manual/en/book.json.php
545
            self::$SUPPORT['json'] = self::json_loaded();
546
547
            // http://php.net/manual/en/book.pcre.php
548
            self::$SUPPORT['pcre_utf8'] = self::pcre_utf8_support();
549
550
            self::$SUPPORT['symfony_polyfill_used'] = self::symfony_polyfill_used();
551
            if (self::$SUPPORT['symfony_polyfill_used'] === true) {
552
                \mb_internal_encoding('UTF-8');
553
                self::$SUPPORT['mbstring_internal_encoding'] = 'UTF-8';
554
            }
555
556
            return true;
557
        }
558
559 5
        return null;
560
    }
561
562
    /**
563
     * Generates a UTF-8 encoded character from the given code point.
564
     *
565
     * INFO: opposite to UTF8::ord()
566
     *
567
     * EXAMPLE: <code>UTF8::chr(0x2603); // '☃'</code>
568
     *
569
     * @param int    $code_point <p>The code point for which to generate a character.</p>
570
     * @param string $encoding   [optional] <p>Default is UTF-8</p>
571
     *
572
     * @psalm-pure
573
     *
574
     * @return string|null
575
     *                     <p>Multi-byte character, returns null on failure or empty input.</p>
576
     */
577 21
    public static function chr($code_point, string $encoding = 'UTF-8')
578
    {
579
        // init
580
        /**
581
         * @psalm-suppress ImpureStaticVariable
582
         *
583
         * @var array<string,string>
584
         */
585 21
        static $CHAR_CACHE = [];
586
587 21
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
588 5
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
589
        }
590
591
        /** @noinspection InArrayCanBeUsedInspection */
592
        if (
593 21
            $encoding !== 'UTF-8'
594
            &&
595 21
            $encoding !== 'ISO-8859-1'
596
            &&
597 21
            $encoding !== 'WINDOWS-1252'
598
            &&
599 21
            self::$SUPPORT['mbstring'] === false
600
        ) {
601
            /**
602
             * @psalm-suppress ImpureFunctionCall - is is only a warning
603
             */
604
            \trigger_error('UTF8::chr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
605
        }
606
607 21
        if (!\is_int($code_point) || $code_point <= 0) {
0 ignored issues
show
introduced by
The condition is_int($code_point) is always true.
Loading history...
608 5
            return null;
609
        }
610
611 21
        $cache_key = $code_point . '_' . $encoding;
612 21
        if (isset($CHAR_CACHE[$cache_key])) {
613 19
            return $CHAR_CACHE[$cache_key];
614
        }
615
616 10
        if ($code_point <= 0x80) { // only for "simple"-chars
617
618 9
            if (self::$CHR === null) {
619
                self::$CHR = self::getData('chr');
620
            }
621
622
            /**
623
             * @psalm-suppress PossiblyNullArrayAccess
624
             */
625 9
            $chr = self::$CHR[$code_point];
626
627 9
            if ($encoding !== 'UTF-8') {
628 1
                $chr = self::encode($encoding, $chr);
629
            }
630
631 9
            return $CHAR_CACHE[$cache_key] = $chr;
632
        }
633
634
        //
635
        // fallback via "IntlChar"
636
        //
637
638 6
        if (self::$SUPPORT['intlChar'] === true) {
639
            /** @noinspection PhpComposerExtensionStubsInspection */
640 6
            $chr = \IntlChar::chr($code_point);
641
642 6
            if ($encoding !== 'UTF-8') {
643
                $chr = self::encode($encoding, $chr);
644
            }
645
646 6
            return $CHAR_CACHE[$cache_key] = $chr;
647
        }
648
649
        //
650
        // fallback via vanilla php
651
        //
652
653
        if (self::$CHR === null) {
654
            self::$CHR = self::getData('chr');
655
        }
656
657
        $code_point = (int) $code_point;
658
        if ($code_point <= 0x7FF) {
659
            /**
660
             * @psalm-suppress PossiblyNullArrayAccess
661
             */
662
            $chr = self::$CHR[($code_point >> 6) + 0xC0] .
663
                   self::$CHR[($code_point & 0x3F) + 0x80];
664
        } elseif ($code_point <= 0xFFFF) {
665
            /**
666
             * @psalm-suppress PossiblyNullArrayAccess
667
             */
668
            $chr = self::$CHR[($code_point >> 12) + 0xE0] .
669
                   self::$CHR[(($code_point >> 6) & 0x3F) + 0x80] .
670
                   self::$CHR[($code_point & 0x3F) + 0x80];
671
        } else {
672
            /**
673
             * @psalm-suppress PossiblyNullArrayAccess
674
             */
675
            $chr = self::$CHR[($code_point >> 18) + 0xF0] .
676
                   self::$CHR[(($code_point >> 12) & 0x3F) + 0x80] .
677
                   self::$CHR[(($code_point >> 6) & 0x3F) + 0x80] .
678
                   self::$CHR[($code_point & 0x3F) + 0x80];
679
        }
680
681
        if ($encoding !== 'UTF-8') {
682
            $chr = self::encode($encoding, $chr);
683
        }
684
685
        return $CHAR_CACHE[$cache_key] = $chr;
686
    }
687
688
    /**
689
     * Applies callback to all characters of a string.
690
     *
691
     * EXAMPLE: <code>UTF8::chr_map([UTF8::class, 'strtolower'], 'Κόσμε'); // ['κ','ό', 'σ', 'μ', 'ε']</code>
692
     *
693
     * @param callable $callback <p>The callback function.</p>
694
     * @param string   $str      <p>UTF-8 string to run callback on.</p>
695
     *
696
     * @psalm-pure
697
     *
698
     * @return string[]
699
     *                  <p>The outcome of the callback, as array.</p>
700
     */
701 2
    public static function chr_map($callback, string $str): array
702
    {
703 2
        return \array_map(
704 2
            $callback,
705 2
            self::str_split($str)
706
        );
707
    }
708
709
    /**
710
     * Generates an array of byte length of each character of a Unicode string.
711
     *
712
     * 1 byte => U+0000  - U+007F
713
     * 2 byte => U+0080  - U+07FF
714
     * 3 byte => U+0800  - U+FFFF
715
     * 4 byte => U+10000 - U+10FFFF
716
     *
717
     * EXAMPLE: <code>UTF8::chr_size_list('中文空白-test'); // [3, 3, 3, 3, 1, 1, 1, 1, 1]</code>
718
     *
719
     * @param string $str <p>The original unicode string.</p>
720
     *
721
     * @psalm-pure
722
     *
723
     * @return int[]
724
     *               <p>An array of byte lengths of each character.</p>
725
     */
726 4
    public static function chr_size_list(string $str): array
727
    {
728 4
        if ($str === '') {
729 4
            return [];
730
        }
731
732 4
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
733
            return \array_map(
734
                static function (string $data): int {
735
                    // "mb_" is available if overload is used, so use it ...
736
                    return \mb_strlen($data, 'CP850'); // 8-BIT
737
                },
738
                self::str_split($str)
739
            );
740
        }
741
742 4
        return \array_map('\strlen', self::str_split($str));
743
    }
744
745
    /**
746
     * Get a decimal code representation of a specific character.
747
     *
748
     * INFO: opposite to UTF8::decimal_to_chr()
749
     *
750
     * EXAMPLE: <code>UTF8::chr_to_decimal('§'); // 0xa7</code>
751
     *
752
     * @param string $char <p>The input character.</p>
753
     *
754
     * @psalm-pure
755
     *
756
     * @return int
757
     */
758 5
    public static function chr_to_decimal(string $char): int
759
    {
760 5
        if (self::$SUPPORT['iconv'] === true) {
761 5
            $chr_tmp = \iconv('UTF-8', 'UCS-4LE', $char);
762 5
            if ($chr_tmp !== false) {
763
                /** @noinspection OffsetOperationsInspection */
764 5
                return \unpack('V', $chr_tmp)[1];
765
            }
766
        }
767
768
        $code = self::ord($char[0]);
769
        $bytes = 1;
770
771
        if (!($code & 0x80)) {
772
            // 0xxxxxxx
773
            return $code;
774
        }
775
776
        if (($code & 0xe0) === 0xc0) {
777
            // 110xxxxx
778
            $bytes = 2;
779
            $code &= ~0xc0;
780
        } elseif (($code & 0xf0) === 0xe0) {
781
            // 1110xxxx
782
            $bytes = 3;
783
            $code &= ~0xe0;
784
        } elseif (($code & 0xf8) === 0xf0) {
785
            // 11110xxx
786
            $bytes = 4;
787
            $code &= ~0xf0;
788
        }
789
790
        for ($i = 2; $i <= $bytes; ++$i) {
791
            // 10xxxxxx
792
            $code = ($code << 6) + (self::ord($char[$i - 1]) & ~0x80);
793
        }
794
795
        return $code;
796
    }
797
798
    /**
799
     * Get hexadecimal code point (U+xxxx) of a UTF-8 encoded character.
800
     *
801
     * EXAMPLE: <code>UTF8::chr_to_hex('§'); // U+00a7</code>
802
     *
803
     * @param int|string $char   <p>The input character</p>
804
     * @param string     $prefix [optional]
805
     *
806
     * @psalm-pure
807
     *
808
     * @return string
809
     *                <p>The code point encoded as U+xxxx.</p>
810
     */
811 2
    public static function chr_to_hex($char, string $prefix = 'U+'): string
812
    {
813 2
        if ($char === '') {
814 2
            return '';
815
        }
816
817 2
        if ($char === '&#0;') {
818 2
            $char = '';
819
        }
820
821 2
        return self::int_to_hex(self::ord((string) $char), $prefix);
822
    }
823
824
    /**
825
     * alias for "UTF8::chr_to_decimal()"
826
     *
827
     * @param string $chr
828
     *
829
     * @psalm-pure
830
     *
831
     * @return int
832
     *
833
     * @see        UTF8::chr_to_decimal()
834
     * @deprecated <p>please use "UTF8::chr_to_decimal()"</p>
835
     */
836 2
    public static function chr_to_int(string $chr): int
837
    {
838 2
        return self::chr_to_decimal($chr);
839
    }
840
841
    /**
842
     * Splits a string into smaller chunks and multiple lines, using the specified line ending character.
843
     *
844
     * EXAMPLE: <code>UTF8::chunk_split('ABC-ÖÄÜ-中文空白-κόσμε', 3); // "ABC\r\n-ÖÄ\r\nÜ-中\r\n文空白\r\n-κό\r\nσμε"</code>
845
     *
846
     * @param string $body         <p>The original string to be split.</p>
847
     * @param int    $chunk_length [optional] <p>The maximum character length of a chunk.</p>
848
     * @param string $end          [optional] <p>The character(s) to be inserted at the end of each chunk.</p>
849
     *
850
     * @psalm-pure
851
     *
852
     * @return string
853
     *                <p>The chunked string.</p>
854
     */
855 4
    public static function chunk_split(string $body, int $chunk_length = 76, string $end = "\r\n"): string
856
    {
857 4
        return \implode($end, self::str_split($body, $chunk_length));
858
    }
859
860
    /**
861
     * Accepts a string and removes all non-UTF-8 characters from it + extras if needed.
862
     *
863
     * EXAMPLE: <code>UTF8::clean("\xEF\xBB\xBF„Abcdef\xc2\xa0\x20…” — 😃 - Düsseldorf", true, true); // '„Abcdef  …” — 😃 - Düsseldorf'</code>
864
     *
865
     * @param string $str                                     <p>The string to be sanitized.</p>
866
     * @param bool   $remove_bom                              [optional] <p>Set to true, if you need to remove
867
     *                                                        UTF-BOM.</p>
868
     * @param bool   $normalize_whitespace                    [optional] <p>Set to true, if you need to normalize the
869
     *                                                        whitespace.</p>
870
     * @param bool   $normalize_msword                        [optional] <p>Set to true, if you need to normalize MS
871
     *                                                        Word chars e.g.: "…"
872
     *                                                        => "..."</p>
873
     * @param bool   $keep_non_breaking_space                 [optional] <p>Set to true, to keep non-breaking-spaces,
874
     *                                                        in
875
     *                                                        combination with
876
     *                                                        $normalize_whitespace</p>
877
     * @param bool   $replace_diamond_question_mark           [optional] <p>Set to true, if you need to remove diamond
878
     *                                                        question mark e.g.: "�"</p>
879
     * @param bool   $remove_invisible_characters             [optional] <p>Set to false, if you not want to remove
880
     *                                                        invisible characters e.g.: "\0"</p>
881
     * @param bool   $remove_invisible_characters_url_encoded [optional] <p>Set to true, if you not want to remove
882
     *                                                        invisible url encoded characters e.g.: "%0B"<br> WARNING:
883
     *                                                        maybe contains false-positives e.g. aa%0Baa -> aaaa.
884
     *                                                        </p>
885
     *
886
     * @psalm-pure
887
     *
888
     * @return string
889
     *                <p>An clean UTF-8 encoded string.</p>
890
     *
891
     * @noinspection PhpTooManyParametersInspection
892
     */
893 90
    public static function clean(
894
        string $str,
895
        bool $remove_bom = false,
896
        bool $normalize_whitespace = false,
897
        bool $normalize_msword = false,
898
        bool $keep_non_breaking_space = false,
899
        bool $replace_diamond_question_mark = false,
900
        bool $remove_invisible_characters = true,
901
        bool $remove_invisible_characters_url_encoded = false
902
    ): string {
903
        // http://stackoverflow.com/questions/1401317/remove-non-utf8-characters-from-string
904
        // caused connection reset problem on larger strings
905
906 90
        $regex = '/
907
          (
908
            (?: [\x00-\x7F]               # single-byte sequences   0xxxxxxx
909
            |   [\xC0-\xDF][\x80-\xBF]    # double-byte sequences   110xxxxx 10xxxxxx
910
            |   [\xE0-\xEF][\x80-\xBF]{2} # triple-byte sequences   1110xxxx 10xxxxxx * 2
911
            |   [\xF0-\xF7][\x80-\xBF]{3} # quadruple-byte sequence 11110xxx 10xxxxxx * 3
912
            ){1,100}                      # ...one or more times
913
          )
914
        | ( [\x80-\xBF] )                 # invalid byte in range 10000000 - 10111111
915
        | ( [\xC0-\xFF] )                 # invalid byte in range 11000000 - 11111111
916
        /x';
917
        /** @noinspection NotOptimalRegularExpressionsInspection */
918 90
        $str = (string) \preg_replace($regex, '$1', $str);
919
920 90
        if ($replace_diamond_question_mark) {
921 33
            $str = self::replace_diamond_question_mark($str);
922
        }
923
924 90
        if ($remove_invisible_characters) {
925 90
            $str = self::remove_invisible_characters($str, $remove_invisible_characters_url_encoded);
926
        }
927
928 90
        if ($normalize_whitespace) {
929 37
            $str = self::normalize_whitespace($str, $keep_non_breaking_space);
930
        }
931
932 90
        if ($normalize_msword) {
933 4
            $str = self::normalize_msword($str);
934
        }
935
936 90
        if ($remove_bom) {
937 37
            $str = self::remove_bom($str);
938
        }
939
940 90
        return $str;
941
    }
942
943
    /**
944
     * Clean-up a string and show only printable UTF-8 chars at the end  + fix UTF-8 encoding.
945
     *
946
     * EXAMPLE: <code>UTF8::cleanup("\xEF\xBB\xBF„Abcdef\xc2\xa0\x20…” — 😃 - Düsseldorf", true, true); // '„Abcdef  …” — 😃 - Düsseldorf'</code>
947
     *
948
     * @param string $str <p>The input string.</p>
949
     *
950
     * @psalm-pure
951
     *
952
     * @return string
953
     */
954 33
    public static function cleanup($str): string
955
    {
956
        // init
957 33
        $str = (string) $str;
958
959 33
        if ($str === '') {
960 5
            return '';
961
        }
962
963
        // fixed ISO <-> UTF-8 Errors
964 33
        $str = self::fix_simple_utf8($str);
965
966
        // remove all none UTF-8 symbols
967
        // && remove diamond question mark (�)
968
        // && remove remove invisible characters (e.g. "\0")
969
        // && remove BOM
970
        // && normalize whitespace chars (but keep non-breaking-spaces)
971 33
        return self::clean(
972 33
            $str,
973 33
            true,
974 33
            true,
975 33
            false,
976 33
            true,
977 33
            true
978
        );
979
    }
980
981
    /**
982
     * Accepts a string or a array of strings and returns an array of Unicode code points.
983
     *
984
     * INFO: opposite to UTF8::string()
985
     *
986
     * EXAMPLE: <code>
987
     * UTF8::codepoints('κöñ'); // array(954, 246, 241)
988
     * // ... OR ...
989
     * UTF8::codepoints('κöñ', true); // array('U+03ba', 'U+00f6', 'U+00f1')
990
     * </code>
991
     *
992
     * @param string|string[] $arg         <p>A UTF-8 encoded string or an array of such strings.</p>
993
     * @param bool            $use_u_style <p>If True, will return code points in U+xxxx format,
994
     *                                     default, code points will be returned as integers.</p>
995
     *
996
     * @psalm-pure
997
     *
998
     * @return int[]|string[]
999
     *                        <p>
1000
     *                        The array of code points:<br>
1001
     *                        int[] for $u_style === false<br>
1002
     *                        string[] for $u_style === true<br>
1003
     *                        </p>
1004
     */
1005 12
    public static function codepoints($arg, bool $use_u_style = false): array
1006
    {
1007 12
        if (\is_string($arg)) {
1008 12
            $arg = self::str_split($arg);
1009
        }
1010
1011
        /**
1012
         * @psalm-suppress DocblockTypeContradiction
1013
         */
1014 12
        if (!\is_array($arg)) {
0 ignored issues
show
introduced by
The condition is_array($arg) is always true.
Loading history...
1015 4
            return [];
1016
        }
1017
1018 12
        if ($arg === []) {
1019 7
            return [];
1020
        }
1021
1022 11
        $arg = \array_map(
1023
            [
1024 11
                self::class,
1025
                'ord',
1026
            ],
1027 11
            $arg
1028
        );
1029
1030 11
        if ($use_u_style) {
1031 2
            $arg = \array_map(
1032
                [
1033 2
                    self::class,
1034
                    'int_to_hex',
1035
                ],
1036 2
                $arg
1037
            );
1038
        }
1039
1040 11
        return $arg;
1041
    }
1042
1043
    /**
1044
     * Trims the string and replaces consecutive whitespace characters with a
1045
     * single space. This includes tabs and newline characters, as well as
1046
     * multibyte whitespace such as the thin space and ideographic space.
1047
     *
1048
     * @param string $str <p>The input string.</p>
1049
     *
1050
     * @psalm-pure
1051
     *
1052
     * @return string
1053
     *                <p>A string with trimmed $str and condensed whitespace.</p>
1054
     */
1055 13
    public static function collapse_whitespace(string $str): string
1056
    {
1057 13
        if (self::$SUPPORT['mbstring'] === true) {
1058
            /** @noinspection PhpComposerExtensionStubsInspection */
1059 13
            return \trim((string) \mb_ereg_replace('[[:space:]]+', ' ', $str));
1060
        }
1061
1062
        return \trim(self::regex_replace($str, '[[:space:]]+', ' '));
1063
    }
1064
1065
    /**
1066
     * Returns count of characters used in a string.
1067
     *
1068
     * EXAMPLE: <code>UTF8::count_chars('κaκbκc'); // array('κ' => 3, 'a' => 1, 'b' => 1, 'c' => 1)</code>
1069
     *
1070
     * @param string $str                     <p>The input string.</p>
1071
     * @param bool   $clean_utf8              [optional] <p>Remove non UTF-8 chars from the string.</p>
1072
     * @param bool   $try_to_use_mb_functions [optional] <p>Set to false, if you don't want to use
1073
     *
1074
     * @psalm-pure
1075
     *
1076
     * @return int[]
1077
     *               <p>An associative array of Character as keys and
1078
     *               their count as values.</p>
1079
     */
1080 19
    public static function count_chars(
1081
        string $str,
1082
        bool $clean_utf8 = false,
1083
        bool $try_to_use_mb_functions = true
1084
    ): array {
1085 19
        return \array_count_values(
1086 19
            self::str_split(
1087 19
                $str,
1088 19
                1,
1089 19
                $clean_utf8,
1090 19
                $try_to_use_mb_functions
1091
            )
1092
        );
1093
    }
1094
1095
    /**
1096
     * Create a valid CSS identifier for e.g. "class"- or "id"-attributes.
1097
     *
1098
     * EXAMPLE: <code>UTF8::css_identifier('123foo/bar!!!'); // _23foo-bar</code>
1099
     *
1100
     * copy&past from https://github.com/drupal/core/blob/8.8.x/lib/Drupal/Component/Utility/Html.php#L95
1101
     *
1102
     * @param string   $str        <p>INFO: if no identifier is given e.g. " " or "", we will create a unique string automatically</p>
1103
     * @param string[] $filter
1104
     * @param bool     $strip_tags
1105
     * @param bool     $strtolower
1106
     *
1107
     * @psalm-pure
1108
     *
1109
     * @return string
1110
     *
1111
     * @phpstan-param array<string,string> $filter
1112
     */
1113 1
    public static function css_identifier(
1114
        string $str = '',
1115
        array $filter = [
1116
            ' ' => '-',
1117
            '/' => '-',
1118
            '[' => '',
1119
            ']' => '',
1120
        ],
1121
        bool $strip_tags = false,
1122
        bool $strtolower = true
1123
    ): string {
1124
        // We could also use strtr() here but its much slower than str_replace(). In
1125
        // order to keep '__' to stay '__' we first replace it with a different
1126
        // placeholder after checking that it is not defined as a filter.
1127 1
        $double_underscore_replacements = 0;
1128
1129
        // Fallback ...
1130 1
        if (\trim($str) === '') {
1131 1
            $str = \uniqid('auto-generated-css-class', true);
1132
        } else {
1133 1
            $str = self::clean($str);
1134
        }
1135
1136 1
        if ($strip_tags) {
1137
            $str = \strip_tags($str);
1138
        }
1139
1140 1
        if ($strtolower) {
1141 1
            $str = \strtolower($str);
1142
        }
1143
1144 1
        if (!isset($filter['__'])) {
1145 1
            $str = \str_replace('__', '##', $str, $double_underscore_replacements);
1146
        }
1147
1148
        /* @noinspection ArrayValuesMissUseInspection */
1149 1
        $str = \str_replace(\array_keys($filter), \array_values($filter), $str);
1150
        // Replace temporary placeholder '##' with '__' only if the original
1151
        // $identifier contained '__'.
1152 1
        if ($double_underscore_replacements > 0) {
1153
            $str = \str_replace('##', '__', $str);
1154
        }
1155
1156
        // Valid characters in a CSS identifier are:
1157
        // - the hyphen (U+002D)
1158
        // - a-z (U+0030 - U+0039)
1159
        // - A-Z (U+0041 - U+005A)
1160
        // - the underscore (U+005F)
1161
        // - 0-9 (U+0061 - U+007A)
1162
        // - ISO 10646 characters U+00A1 and higher
1163
        // We strip out any character not in the above list.
1164 1
        $str = (string) \preg_replace('/[^\x{002D}\x{0030}-\x{0039}\x{0041}-\x{005A}\x{005F}\x{0061}-\x{007A}\x{00A1}-\x{FFFF}]/u', '', $str);
1165
        // Identifiers cannot start with a digit, two hyphens, or a hyphen followed by a digit.
1166 1
        $str = (string) \preg_replace(['/^[0-9]/', '/^(-[0-9])|^(--)/'], ['_', '__'], $str);
1167
1168 1
        return \trim($str, '-');
1169
    }
1170
1171
    /**
1172
     * Remove css media-queries.
1173
     *
1174
     * @param string $str
1175
     *
1176
     * @psalm-pure
1177
     *
1178
     * @return string
1179
     */
1180 1
    public static function css_stripe_media_queries(string $str): string
1181
    {
1182 1
        return (string) \preg_replace(
1183 1
            '#@media\\s+(?:only\\s)?(?:[\\s{(]|screen|all)\\s?[^{]+{.*}\\s*}\\s*#isumU',
1184 1
            '',
1185 1
            $str
1186
        );
1187
    }
1188
1189
    /**
1190
     * Checks whether ctype is available on the server.
1191
     *
1192
     * @psalm-pure
1193
     *
1194
     * @return bool
1195
     *              <p><strong>true</strong> if available, <strong>false</strong> otherwise</p>
1196
     *
1197
     * @internal <p>Please do not use it anymore, we will make is private in next major version.</p>
1198
     */
1199
    public static function ctype_loaded(): bool
1200
    {
1201
        return \extension_loaded('ctype');
1202
    }
1203
1204
    /**
1205
     * Converts an int value into a UTF-8 character.
1206
     *
1207
     * INFO: opposite to UTF8::string()
1208
     *
1209
     * EXAMPLE: <code>UTF8::decimal_to_chr(931); // 'Σ'</code>
1210
     *
1211
     * @param int|string $int
1212
     *
1213
     * @phpstan-param int|numeric-string $int
1214
     *
1215
     * @psalm-pure
1216
     *
1217
     * @return string
1218
     */
1219 20
    public static function decimal_to_chr($int): string
1220
    {
1221 20
        return self::html_entity_decode('&#' . $int . ';', \ENT_QUOTES | \ENT_HTML5);
1222
    }
1223
1224
    /**
1225
     * Decodes a MIME header field
1226
     *
1227
     * @param string $str
1228
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
1229
     *
1230
     * @psalm-pure
1231
     *
1232
     * @return false|string
1233
     *                      <p>A decoded MIME field on success,
1234
     *                      or false if an error occurs during the decoding.</p>
1235
     */
1236 2
    public static function decode_mimeheader($str, string $encoding = 'UTF-8')
1237
    {
1238 2
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
1239 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
1240
        }
1241
1242
        // always fallback via symfony polyfill
1243 2
        return \iconv_mime_decode($str, \ICONV_MIME_DECODE_CONTINUE_ON_ERROR, $encoding);
1244
    }
1245
1246
    /**
1247
     * Convert any two-letter country code (ISO 3166-1) to the corresponding Emoji.
1248
     *
1249
     * @see https://en.wikipedia.org/wiki/ISO_3166-1
1250
     *
1251
     * @param string $country_code_iso_3166_1 <p>e.g. DE</p>
1252
     *
1253
     * @return string
1254
     *                <p>Emoji or empty string on error.</p>
1255
     */
1256 1
    public static function emoji_from_country_code(string $country_code_iso_3166_1): string
1257
    {
1258 1
        if ($country_code_iso_3166_1 === '') {
1259 1
            return '';
1260
        }
1261
1262 1
        if (self::strlen($country_code_iso_3166_1) !== 2) {
1263 1
            return '';
1264
        }
1265
1266 1
        $country_code_iso_3166_1 = \strtoupper($country_code_iso_3166_1);
1267
1268 1
        $flagOffset = 0x1F1E6;
1269 1
        $asciiOffset = 0x41;
1270
1271 1
        return (self::chr((self::ord($country_code_iso_3166_1[0]) - $asciiOffset + $flagOffset)) ?? '') .
1272 1
               (self::chr((self::ord($country_code_iso_3166_1[1]) - $asciiOffset + $flagOffset)) ?? '');
1273
    }
1274
1275
    /**
1276
     * Decodes a string which was encoded by "UTF8::emoji_encode()".
1277
     *
1278
     * INFO: opposite to UTF8::emoji_encode()
1279
     *
1280
     * EXAMPLE: <code>
1281
     * UTF8::emoji_decode('foo CHARACTER_OGRE', false); // 'foo 👹'
1282
     * //
1283
     * UTF8::emoji_decode('foo _-_PORTABLE_UTF8_-_308095726_-_627590803_-_8FTU_ELBATROP_-_', true); // 'foo 👹'
1284
     * </code>
1285
     *
1286
     * @param string $str                            <p>The input string.</p>
1287
     * @param bool   $use_reversible_string_mappings [optional] <p>
1288
     *                                               When <b>TRUE</b>, we se a reversible string mapping
1289
     *                                               between "emoji_encode" and "emoji_decode".</p>
1290
     *
1291
     * @psalm-pure
1292
     *
1293
     * @return string
1294
     */
1295 9
    public static function emoji_decode(
1296
        string $str,
1297
        bool $use_reversible_string_mappings = false
1298
    ): string {
1299 9
        self::initEmojiData();
1300
1301 9
        if ($use_reversible_string_mappings) {
1302 9
            return (string) \str_replace(
1303 9
                (array) self::$EMOJI_KEYS_REVERSIBLE_CACHE,
1304 9
                (array) self::$EMOJI_VALUES_CACHE,
1305 9
                $str
1306
            );
1307
        }
1308
1309 1
        return (string) \str_replace(
1310 1
            (array) self::$EMOJI_KEYS_CACHE,
1311 1
            (array) self::$EMOJI_VALUES_CACHE,
1312 1
            $str
1313
        );
1314
    }
1315
1316
    /**
1317
     * Encode a string with emoji chars into a non-emoji string.
1318
     *
1319
     * INFO: opposite to UTF8::emoji_decode()
1320
     *
1321
     * EXAMPLE: <code>
1322
     * UTF8::emoji_encode('foo 👹', false)); // 'foo CHARACTER_OGRE'
1323
     * //
1324
     * UTF8::emoji_encode('foo 👹', true)); // 'foo _-_PORTABLE_UTF8_-_308095726_-_627590803_-_8FTU_ELBATROP_-_'
1325
     * </code>
1326
     *
1327
     * @param string $str                            <p>The input string</p>
1328
     * @param bool   $use_reversible_string_mappings [optional] <p>
1329
     *                                               when <b>TRUE</b>, we use a reversible string mapping
1330
     *                                               between "emoji_encode" and "emoji_decode"</p>
1331
     *
1332
     * @psalm-pure
1333
     *
1334
     * @return string
1335
     */
1336 12
    public static function emoji_encode(
1337
        string $str,
1338
        bool $use_reversible_string_mappings = false
1339
    ): string {
1340 12
        self::initEmojiData();
1341
1342 12
        if ($use_reversible_string_mappings) {
1343 9
            return (string) \str_replace(
1344 9
                (array) self::$EMOJI_VALUES_CACHE,
1345 9
                (array) self::$EMOJI_KEYS_REVERSIBLE_CACHE,
1346 9
                $str
1347
            );
1348
        }
1349
1350 4
        return (string) \str_replace(
1351 4
            (array) self::$EMOJI_VALUES_CACHE,
1352 4
            (array) self::$EMOJI_KEYS_CACHE,
1353 4
            $str
1354
        );
1355
    }
1356
1357
    /**
1358
     * Encode a string with a new charset-encoding.
1359
     *
1360
     * INFO:  This function will also try to fix broken / double encoding,
1361
     *        so you can call this function also on a UTF-8 string and you don't mess up the string.
1362
     *
1363
     * EXAMPLE: <code>
1364
     * UTF8::encode('ISO-8859-1', '-ABC-中文空白-'); // '-ABC-????-'
1365
     * //
1366
     * UTF8::encode('UTF-8', '-ABC-中文空白-'); // '-ABC-中文空白-'
1367
     * //
1368
     * UTF8::encode('HTML', '-ABC-中文空白-'); // '-ABC-&#20013;&#25991;&#31354;&#30333;-'
1369
     * //
1370
     * UTF8::encode('BASE64', '-ABC-中文空白-'); // 'LUFCQy3kuK3mlofnqbrnmb0t'
1371
     * </code>
1372
     *
1373
     * @param string $to_encoding                   <p>e.g. 'UTF-16', 'UTF-8', 'ISO-8859-1', etc.</p>
1374
     * @param string $str                           <p>The input string</p>
1375
     * @param bool   $auto_detect_the_from_encoding [optional] <p>Force the new encoding (we try to fix broken / double
1376
     *                                              encoding for UTF-8)<br> otherwise we auto-detect the current
1377
     *                                              string-encoding</p>
1378
     * @param string $from_encoding                 [optional] <p>e.g. 'UTF-16', 'UTF-8', 'ISO-8859-1', etc.<br>
1379
     *                                              A empty string will trigger the autodetect anyway.</p>
1380
     *
1381
     * @psalm-pure
1382
     *
1383
     * @return string
1384
     *
1385
     * @psalm-suppress InvalidReturnStatement
1386
     */
1387 29
    public static function encode(
1388
        string $to_encoding,
1389
        string $str,
1390
        bool $auto_detect_the_from_encoding = true,
1391
        string $from_encoding = ''
1392
    ): string {
1393 29
        if ($str === '' || $to_encoding === '') {
1394 13
            return $str;
1395
        }
1396
1397 29
        if ($to_encoding !== 'UTF-8' && $to_encoding !== 'CP850') {
1398 7
            $to_encoding = self::normalize_encoding($to_encoding, 'UTF-8');
1399
        }
1400
1401 29
        if ($from_encoding && $from_encoding !== 'UTF-8' && $from_encoding !== 'CP850') {
1402 2
            $from_encoding = self::normalize_encoding($from_encoding);
1403
        }
1404
1405
        if (
1406 29
            $to_encoding
1407
            &&
1408 29
            $from_encoding
1409
            &&
1410 29
            $from_encoding === $to_encoding
1411
        ) {
1412
            return $str;
1413
        }
1414
1415 29
        if ($to_encoding === 'JSON') {
1416 1
            $return = self::json_encode($str);
1417 1
            if ($return === false) {
1418
                throw new \InvalidArgumentException('The input string [' . $str . '] can not be used for json_encode().');
1419
            }
1420
1421 1
            return $return;
1422
        }
1423 29
        if ($from_encoding === 'JSON') {
1424 1
            $str = self::json_decode($str);
1425 1
            $from_encoding = '';
1426
        }
1427
1428 29
        if ($to_encoding === 'BASE64') {
1429 2
            return \base64_encode($str);
1430
        }
1431 29
        if ($from_encoding === 'BASE64') {
1432 2
            $str = \base64_decode($str, true);
1433 2
            $from_encoding = '';
1434
        }
1435
1436 29
        if ($to_encoding === 'HTML-ENTITIES') {
1437 2
            return self::html_encode($str, true);
1438
        }
1439 29
        if ($from_encoding === 'HTML-ENTITIES') {
1440 2
            $str = self::html_entity_decode($str, \ENT_COMPAT);
1441 2
            $from_encoding = '';
1442
        }
1443
1444 29
        $from_encoding_auto_detected = false;
1445
        if (
1446 29
            $auto_detect_the_from_encoding
1447
            ||
1448 29
            !$from_encoding
1449
        ) {
1450 29
            $from_encoding_auto_detected = self::str_detect_encoding($str);
1451
        }
1452
1453
        // DEBUG
1454
        //var_dump($to_encoding, $from_encoding, $from_encoding_auto_detected, $str, "\n\n");
1455
1456 29
        if ($from_encoding_auto_detected !== false) {
1457
            /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
1458 25
            $from_encoding = $from_encoding_auto_detected;
1459 7
        } elseif ($auto_detect_the_from_encoding) {
1460
            // fallback for the "autodetect"-mode
1461 7
            return self::to_utf8($str);
1462
        }
1463
1464
        if (
1465 25
            !$from_encoding
1466
            ||
1467 25
            $from_encoding === $to_encoding
1468
        ) {
1469 15
            return $str;
1470
        }
1471
1472
        if (
1473 20
            $to_encoding === 'UTF-8'
1474
            &&
1475
            (
1476 18
                $from_encoding === 'WINDOWS-1252'
1477
                ||
1478 20
                $from_encoding === 'ISO-8859-1'
1479
            )
1480
        ) {
1481 14
            return self::to_utf8($str);
1482
        }
1483
1484
        if (
1485 12
            $to_encoding === 'ISO-8859-1'
1486
            &&
1487
            (
1488 6
                $from_encoding === 'WINDOWS-1252'
1489
                ||
1490 12
                $from_encoding === 'UTF-8'
1491
            )
1492
        ) {
1493 6
            return self::to_iso8859($str);
1494
        }
1495
1496
        /** @noinspection InArrayCanBeUsedInspection */
1497
        if (
1498 10
            $to_encoding !== 'UTF-8'
1499
            &&
1500 10
            $to_encoding !== 'ISO-8859-1'
1501
            &&
1502 10
            $to_encoding !== 'WINDOWS-1252'
1503
            &&
1504 10
            self::$SUPPORT['mbstring'] === false
1505
        ) {
1506
            /**
1507
             * @psalm-suppress ImpureFunctionCall - is is only a warning
1508
             */
1509
            \trigger_error('UTF8::encode() without mbstring cannot handle "' . $to_encoding . '" encoding', \E_USER_WARNING);
1510
        }
1511
1512 10
        if (self::$SUPPORT['mbstring'] === true) {
1513
            // warning: do not use the symfony polyfill here
1514 10
            $str_encoded = \mb_convert_encoding(
1515 10
                $str,
1516 10
                $to_encoding,
1517 10
                $from_encoding
1518
            );
1519
1520 10
            if ($str_encoded) {
1521 10
                \assert(\is_string($str_encoded));
1522
1523 10
                return $str_encoded;
1524
            }
1525
        }
1526
1527
        /** @noinspection PhpUsageOfSilenceOperatorInspection - Detected an incomplete multibyte character in input string */
1528
        $return = @\iconv($from_encoding, $to_encoding, $str);
1529
        if ($return !== false) {
1530
            return $return;
1531
        }
1532
1533
        return $str;
1534
    }
1535
1536
    /**
1537
     * @param string $str
1538
     * @param string $from_charset      [optional] <p>Set the input charset.</p>
1539
     * @param string $to_charset        [optional] <p>Set the output charset.</p>
1540
     * @param string $transfer_encoding [optional] <p>Set the transfer encoding.</p>
1541
     * @param string $linefeed          [optional] <p>Set the used linefeed.</p>
1542
     * @param int    $indent            [optional] <p>Set the max length indent.</p>
1543
     *
1544
     * @psalm-pure
1545
     *
1546
     * @return false|string
1547
     *                      <p>An encoded MIME field on success,
1548
     *                      or false if an error occurs during the encoding.</p>
1549
     */
1550 1
    public static function encode_mimeheader(
1551
        string $str,
1552
        string $from_charset = 'UTF-8',
1553
        string $to_charset = 'UTF-8',
1554
        string $transfer_encoding = 'Q',
1555
        string $linefeed = "\r\n",
1556
        int $indent = 76
1557
    ) {
1558 1
        if ($from_charset !== 'UTF-8' && $from_charset !== 'CP850') {
1559
            $from_charset = self::normalize_encoding($from_charset, 'UTF-8');
1560
        }
1561
1562 1
        if ($to_charset !== 'UTF-8' && $to_charset !== 'CP850') {
1563 1
            $to_charset = self::normalize_encoding($to_charset, 'UTF-8');
1564
        }
1565
1566
        // always fallback via symfony polyfill
1567 1
        return \iconv_mime_encode(
1568 1
            '',
1569 1
            $str,
1570
            [
1571 1
                'scheme'           => $transfer_encoding,
1572 1
                'line-length'      => $indent,
1573 1
                'input-charset'    => $from_charset,
1574 1
                'output-charset'   => $to_charset,
1575 1
                'line-break-chars' => $linefeed,
1576
            ]
1577
        );
1578
    }
1579
1580
    /**
1581
     * Create an extract from a sentence, so if the search-string was found, it try to centered in the output.
1582
     *
1583
     * @param string   $str                       <p>The input string.</p>
1584
     * @param string   $search                    <p>The searched string.</p>
1585
     * @param int|null $length                    [optional] <p>Default: null === text->length / 2</p>
1586
     * @param string   $replacer_for_skipped_text [optional] <p>Default: …</p>
1587
     * @param string   $encoding                  [optional] <p>Set the charset for e.g. "mb_" function</p>
1588
     *
1589
     * @psalm-pure
1590
     *
1591
     * @return string
1592
     */
1593 1
    public static function extract_text(
1594
        string $str,
1595
        string $search = '',
1596
        int $length = null,
1597
        string $replacer_for_skipped_text = '…',
1598
        string $encoding = 'UTF-8'
1599
    ): string {
1600 1
        if ($str === '') {
1601 1
            return '';
1602
        }
1603
1604 1
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
1605
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
1606
        }
1607
1608 1
        $trim_chars = "\t\r\n -_()!~?=+/*\\,.:;\"'[]{}`&";
1609
1610 1
        if ($length === null) {
1611 1
            $length = (int) \round((int) self::strlen($str, $encoding) / 2);
1612
        }
1613
1614 1
        if ($search === '') {
1615 1
            if ($encoding === 'UTF-8') {
1616 1
                if ($length > 0) {
1617 1
                    $string_length = (int) \mb_strlen($str);
1618 1
                    $end = ($length - 1) > $string_length ? $string_length : ($length - 1);
1619
                } else {
1620 1
                    $end = 0;
1621
                }
1622
1623 1
                $pos = (int) \min(
1624 1
                    \mb_strpos($str, ' ', $end),
1625 1
                    \mb_strpos($str, '.', $end)
1626
                );
1627
            } else {
1628
                if ($length > 0) {
1629
                    $string_length = (int) self::strlen($str, $encoding);
1630
                    $end = ($length - 1) > $string_length ? $string_length : ($length - 1);
1631
                } else {
1632
                    $end = 0;
1633
                }
1634
1635
                $pos = (int) \min(
1636
                    self::strpos($str, ' ', $end, $encoding),
1637
                    self::strpos($str, '.', $end, $encoding)
1638
                );
1639
            }
1640
1641 1
            if ($pos) {
1642 1
                if ($encoding === 'UTF-8') {
1643 1
                    $str_sub = \mb_substr($str, 0, $pos);
1644
                } else {
1645
                    $str_sub = self::substr($str, 0, $pos, $encoding);
1646
                }
1647
1648 1
                if ($str_sub === false) {
1649
                    return '';
1650
                }
1651
1652 1
                return \rtrim($str_sub, $trim_chars) . $replacer_for_skipped_text;
1653
            }
1654
1655
            return $str;
1656
        }
1657
1658 1
        if ($encoding === 'UTF-8') {
1659 1
            $word_position = (int) \mb_stripos($str, $search);
1660 1
            $half_side = (int) ($word_position - $length / 2 + (int) \mb_strlen($search) / 2);
1661
        } else {
1662
            $word_position = (int) self::stripos($str, $search, 0, $encoding);
1663
            $half_side = (int) ($word_position - $length / 2 + (int) self::strlen($search, $encoding) / 2);
1664
        }
1665
1666 1
        $pos_start = 0;
1667 1
        if ($half_side > 0) {
1668 1
            if ($encoding === 'UTF-8') {
1669 1
                $half_text = \mb_substr($str, 0, $half_side);
1670
            } else {
1671
                $half_text = self::substr($str, 0, $half_side, $encoding);
1672
            }
1673 1
            if ($half_text !== false) {
1674 1
                if ($encoding === 'UTF-8') {
1675 1
                    $pos_start = (int) \max(
1676 1
                        \mb_strrpos($half_text, ' '),
1677 1
                        \mb_strrpos($half_text, '.')
1678
                    );
1679
                } else {
1680
                    $pos_start = (int) \max(
1681
                        self::strrpos($half_text, ' ', 0, $encoding),
1682
                        self::strrpos($half_text, '.', 0, $encoding)
1683
                    );
1684
                }
1685
            }
1686
        }
1687
1688 1
        if ($word_position && $half_side > 0) {
1689 1
            $offset = $pos_start + $length - 1;
1690 1
            $real_length = (int) self::strlen($str, $encoding);
1691
1692 1
            if ($offset > $real_length) {
1693
                $offset = $real_length;
1694
            }
1695
1696 1
            if ($encoding === 'UTF-8') {
1697 1
                $pos_end = (int) \min(
1698 1
                    \mb_strpos($str, ' ', $offset),
1699 1
                    \mb_strpos($str, '.', $offset)
1700 1
                ) - $pos_start;
1701
            } else {
1702
                $pos_end = (int) \min(
1703
                    self::strpos($str, ' ', $offset, $encoding),
1704
                    self::strpos($str, '.', $offset, $encoding)
1705
                ) - $pos_start;
1706
            }
1707
1708 1
            if (!$pos_end || $pos_end <= 0) {
1709 1
                if ($encoding === 'UTF-8') {
1710 1
                    $str_sub = \mb_substr($str, $pos_start, (int) \mb_strlen($str));
1711
                } else {
1712
                    $str_sub = self::substr($str, $pos_start, (int) self::strlen($str, $encoding), $encoding);
1713
                }
1714 1
                if ($str_sub !== false) {
1715 1
                    $extract = $replacer_for_skipped_text . \ltrim($str_sub, $trim_chars);
1716
                } else {
1717 1
                    $extract = '';
1718
                }
1719
            } else {
1720 1
                if ($encoding === 'UTF-8') {
1721 1
                    $str_sub = \mb_substr($str, $pos_start, $pos_end);
1722
                } else {
1723
                    $str_sub = self::substr($str, $pos_start, $pos_end, $encoding);
1724
                }
1725 1
                if ($str_sub !== false) {
1726 1
                    $extract = $replacer_for_skipped_text . \trim($str_sub, $trim_chars) . $replacer_for_skipped_text;
1727
                } else {
1728 1
                    $extract = '';
1729
                }
1730
            }
1731
        } else {
1732 1
            $offset = $length - 1;
1733 1
            $true_length = (int) self::strlen($str, $encoding);
1734
1735 1
            if ($offset > $true_length) {
1736
                $offset = $true_length;
1737
            }
1738
1739 1
            if ($encoding === 'UTF-8') {
1740 1
                $pos_end = (int) \min(
1741 1
                    \mb_strpos($str, ' ', $offset),
1742 1
                    \mb_strpos($str, '.', $offset)
1743
                );
1744
            } else {
1745
                $pos_end = (int) \min(
1746
                    self::strpos($str, ' ', $offset, $encoding),
1747
                    self::strpos($str, '.', $offset, $encoding)
1748
                );
1749
            }
1750
1751 1
            if ($pos_end) {
1752 1
                if ($encoding === 'UTF-8') {
1753 1
                    $str_sub = \mb_substr($str, 0, $pos_end);
1754
                } else {
1755
                    $str_sub = self::substr($str, 0, $pos_end, $encoding);
1756
                }
1757 1
                if ($str_sub !== false) {
1758 1
                    $extract = \rtrim($str_sub, $trim_chars) . $replacer_for_skipped_text;
1759
                } else {
1760 1
                    $extract = '';
1761
                }
1762
            } else {
1763 1
                $extract = $str;
1764
            }
1765
        }
1766
1767 1
        return $extract;
1768
    }
1769
1770
    /**
1771
     * Reads entire file into a string.
1772
     *
1773
     * EXAMPLE: <code>UTF8::file_get_contents('utf16le.txt'); // ...</code>
1774
     *
1775
     * WARNING: Do not use UTF-8 Option ($convert_to_utf8) for binary files (e.g.: images) !!!
1776
     *
1777
     * @see http://php.net/manual/en/function.file-get-contents.php
1778
     *
1779
     * @param string        $filename         <p>
1780
     *                                        Name of the file to read.
1781
     *                                        </p>
1782
     * @param bool          $use_include_path [optional] <p>
1783
     *                                        Prior to PHP 5, this parameter is called
1784
     *                                        use_include_path and is a bool.
1785
     *                                        As of PHP 5 the FILE_USE_INCLUDE_PATH can be used
1786
     *                                        to trigger include path
1787
     *                                        search.
1788
     *                                        </p>
1789
     * @param resource|null $context          [optional] <p>
1790
     *                                        A valid context resource created with
1791
     *                                        stream_context_create. If you don't need to use a
1792
     *                                        custom context, you can skip this parameter by &null;.
1793
     *                                        </p>
1794
     * @param int|null      $offset           [optional] <p>
1795
     *                                        The offset where the reading starts.
1796
     *                                        </p>
1797
     * @param int|null      $max_length       [optional] <p>
1798
     *                                        Maximum length of data read. The default is to read until end
1799
     *                                        of file is reached.
1800
     *                                        </p>
1801
     * @param int           $timeout          <p>The time in seconds for the timeout.</p>
1802
     * @param bool          $convert_to_utf8  <strong>WARNING!!!</strong> <p>Maybe you can't use this option for
1803
     *                                        some files, because they used non default utf-8 chars. Binary files
1804
     *                                        like images or pdf will not be converted.</p>
1805
     * @param string        $from_encoding    [optional] <p>e.g. 'UTF-16', 'UTF-8', 'ISO-8859-1', etc.<br>
1806
     *                                        A empty string will trigger the autodetect anyway.</p>
1807
     *
1808
     * @psalm-pure
1809
     *
1810
     * @return false|string
1811
     *                      <p>The function returns the read data as string or <b>false</b> on failure.</p>
1812
     *
1813
     * @noinspection PhpTooManyParametersInspection
1814
     */
1815 12
    public static function file_get_contents(
1816
        string $filename,
1817
        bool $use_include_path = false,
1818
        $context = null,
1819
        int $offset = null,
1820
        int $max_length = null,
1821
        int $timeout = 10,
1822
        bool $convert_to_utf8 = true,
1823
        string $from_encoding = ''
1824
    ) {
1825
        // init
1826 12
        $filename = \filter_var($filename, \FILTER_SANITIZE_STRING);
1827
        /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
1828 12
        if ($filename === false) {
1829
            return false;
1830
        }
1831
1832 12
        if ($timeout && $context === null) {
1833 9
            $context = \stream_context_create(
1834
                [
1835
                    'http' => [
1836 9
                        'timeout' => $timeout,
1837
                    ],
1838
                ]
1839
            );
1840
        }
1841
1842 12
        if ($offset === null) {
1843 12
            $offset = 0;
1844
        }
1845
1846 12
        if (\is_int($max_length)) {
1847 2
            $data = \file_get_contents($filename, $use_include_path, $context, $offset, $max_length);
1848
        } else {
1849 12
            $data = \file_get_contents($filename, $use_include_path, $context, $offset);
1850
        }
1851
1852
        // return false on error
1853 12
        if ($data === false) {
1854
            return false;
1855
        }
1856
1857 12
        if ($convert_to_utf8) {
1858
            if (
1859 12
                !self::is_binary($data, true)
1860
                ||
1861 9
                self::is_utf16($data, false) !== false
1862
                ||
1863 12
                self::is_utf32($data, false) !== false
1864
            ) {
1865 9
                $data = self::encode('UTF-8', $data, false, $from_encoding);
1866 9
                $data = self::cleanup($data);
1867
            }
1868
        }
1869
1870 12
        return $data;
1871
    }
1872
1873
    /**
1874
     * Checks if a file starts with BOM (Byte Order Mark) character.
1875
     *
1876
     * EXAMPLE: <code>UTF8::file_has_bom('utf8_with_bom.txt'); // true</code>
1877
     *
1878
     * @param string $file_path <p>Path to a valid file.</p>
1879
     *
1880
     * @throws \RuntimeException if file_get_contents() returned false
1881
     *
1882
     * @return bool
1883
     *              <p><strong>true</strong> if the file has BOM at the start, <strong>false</strong> otherwise</p>
1884
     *
1885
     * @psalm-pure
1886
     */
1887 2
    public static function file_has_bom(string $file_path): bool
1888
    {
1889 2
        $file_content = \file_get_contents($file_path);
1890 2
        if ($file_content === false) {
1891
            throw new \RuntimeException('file_get_contents() returned false for:' . $file_path);
1892
        }
1893
1894 2
        return self::string_has_bom($file_content);
1895
    }
1896
1897
    /**
1898
     * Normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
1899
     *
1900
     * EXAMPLE: <code>UTF8::filter(array("\xE9", 'à', 'a')); // array('é', 'à', 'a')</code>
1901
     *
1902
     * @param array|object|string $var
1903
     * @param int                 $normalization_form
1904
     * @param string              $leading_combining
1905
     *
1906
     * @psalm-pure
1907
     *
1908
     * @return mixed
1909
     *
1910
     * @template TFilter
1911
     * @phpstan-param TFilter $var
1912
     * @phpstan-return TFilter
1913
     */
1914 65
    public static function filter(
1915
        $var,
1916
        int $normalization_form = \Normalizer::NFC,
1917
        string $leading_combining = '◌'
1918
    ) {
1919 65
        switch (\gettype($var)) {
1920 65
            case 'object':
1921 65
            case 'array':
1922 6
                foreach ($var as $k => &$v) {
1923 6
                    $v = self::filter($v, $normalization_form, $leading_combining);
1924
                }
1925 6
                unset($v);
1926
1927 6
                break;
1928 65
            case 'string':
1929
1930 63
                if (\strpos($var, "\r") !== false) {
1931 3
                    $var = self::normalize_line_ending($var);
1932
                }
1933
1934 63
                if (!ASCII::is_ascii($var)) {
1935 33
                    if (\Normalizer::isNormalized($var, $normalization_form)) {
1936 27
                        $n = '-';
1937
                    } else {
1938 13
                        $n = \Normalizer::normalize($var, $normalization_form);
1939
1940 13
                        if (isset($n[0])) {
1941 7
                            $var = $n;
1942
                        } else {
1943 9
                            $var = self::encode('UTF-8', $var);
1944
                        }
1945
                    }
1946
1947 33
                    \assert(\is_string($var));
1948
                    if (
1949 33
                        $var[0] >= "\x80"
1950
                        &&
1951 33
                        isset($n[0], $leading_combining[0])
1952
                        &&
1953 33
                        \preg_match('/^\\p{Mn}/u', $var)
1954
                    ) {
1955
                        // Prevent leading combining chars
1956
                        // for NFC-safe concatenations.
1957 3
                        $var = $leading_combining . $var;
1958
                    }
1959
                }
1960
1961 63
                break;
1962
            default:
1963
                // nothing
1964
        }
1965
1966
        /** @noinspection PhpSillyAssignmentInspection */
1967
        /** @phpstan-var TFilter $var */
1968 65
        $var = $var;
1969
1970 65
        return $var;
1971
    }
1972
1973
    /**
1974
     * "filter_input()"-wrapper with normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
1975
     *
1976
     * Gets a specific external variable by name and optionally filters it.
1977
     *
1978
     * EXAMPLE: <code>
1979
     * // _GET['foo'] = 'bar';
1980
     * UTF8::filter_input(INPUT_GET, 'foo', FILTER_SANITIZE_STRING)); // 'bar'
1981
     * </code>
1982
     *
1983
     * @see http://php.net/manual/en/function.filter-input.php
1984
     *
1985
     * @param int            $type          <p>
1986
     *                                      One of <b>INPUT_GET</b>, <b>INPUT_POST</b>,
1987
     *                                      <b>INPUT_COOKIE</b>, <b>INPUT_SERVER</b>, or
1988
     *                                      <b>INPUT_ENV</b>.
1989
     *                                      </p>
1990
     * @param string         $variable_name <p>
1991
     *                                      Name of a variable to get.
1992
     *                                      </p>
1993
     * @param int            $filter        [optional] <p>
1994
     *                                      The ID of the filter to apply. The
1995
     *                                      manual page lists the available filters.
1996
     *                                      </p>
1997
     * @param int|int[]|null $options       [optional] <p>
1998
     *                                      Associative array of options or bitwise disjunction of flags. If filter
1999
     *                                      accepts options, flags can be provided in "flags" field of array.
2000
     *                                      </p>
2001
     *
2002
     * @psalm-pure
2003
     *
2004
     * @return mixed
2005
     *               <p>
2006
     *               Value of the requested variable on success, <b>FALSE</b> if the filter fails, or <b>NULL</b> if the
2007
     *               <i>variable_name</i> variable is not set. If the flag <b>FILTER_NULL_ON_FAILURE</b> is used, it
2008
     *               returns <b>FALSE</b> if the variable is not set and <b>NULL</b> if the filter fails.
2009
     *               </p>
2010
     */
2011 1
    public static function filter_input(
2012
        int $type,
2013
        string $variable_name,
2014
        int $filter = \FILTER_DEFAULT,
2015
        $options = null
2016
    ) {
2017
        /**
2018
         * @psalm-suppress ImpureFunctionCall - we use func_num_args only for args count matching here
2019
         */
2020 1
        if ($options === null || \func_num_args() < 4) {
2021 1
            $var = \filter_input($type, $variable_name, $filter);
2022
        } else {
2023
            $var = \filter_input($type, $variable_name, $filter, $options);
2024
        }
2025
2026 1
        return self::filter($var);
2027
    }
2028
2029
    /**
2030
     * "filter_input_array()"-wrapper with normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
2031
     *
2032
     * Gets external variables and optionally filters them.
2033
     *
2034
     * EXAMPLE: <code>
2035
     * // _GET['foo'] = 'bar';
2036
     * UTF8::filter_input_array(INPUT_GET, array('foo' => 'FILTER_SANITIZE_STRING')); // array('bar')
2037
     * </code>
2038
     *
2039
     * @see http://php.net/manual/en/function.filter-input-array.php
2040
     *
2041
     * @param int        $type       <p>
2042
     *                               One of <b>INPUT_GET</b>, <b>INPUT_POST</b>,
2043
     *                               <b>INPUT_COOKIE</b>, <b>INPUT_SERVER</b>, or
2044
     *                               <b>INPUT_ENV</b>.
2045
     *                               </p>
2046
     * @param array|null $definition [optional] <p>
2047
     *                               An array defining the arguments. A valid key is a string
2048
     *                               containing a variable name and a valid value is either a filter type, or an array
2049
     *                               optionally specifying the filter, flags and options. If the value is an
2050
     *                               array, valid keys are filter which specifies the
2051
     *                               filter type,
2052
     *                               flags which specifies any flags that apply to the
2053
     *                               filter, and options which specifies any options that
2054
     *                               apply to the filter. See the example below for a better understanding.
2055
     *                               </p>
2056
     *                               <p>
2057
     *                               This parameter can be also an integer holding a filter constant. Then all values in the
2058
     *                               input array are filtered by this filter.
2059
     *                               </p>
2060
     * @param bool       $add_empty  [optional] <p>
2061
     *                               Add missing keys as <b>NULL</b> to the return value.
2062
     *                               </p>
2063
     *
2064
     * @psalm-pure
2065
     *
2066
     * @return mixed
2067
     *               <p>
2068
     *               An array containing the values of the requested variables on success, or <b>FALSE</b> on failure.
2069
     *               An array value will be <b>FALSE</b> if the filter fails, or <b>NULL</b> if the variable is not
2070
     *               set. Or if the flag <b>FILTER_NULL_ON_FAILURE</b> is used, it returns <b>FALSE</b> if the variable
2071
     *               is not set and <b>NULL</b> if the filter fails.
2072
     *               </p>
2073
     */
2074 1
    public static function filter_input_array(
2075
        int $type,
2076
        $definition = null,
2077
        bool $add_empty = true
2078
    ) {
2079
        /**
2080
         * @psalm-suppress ImpureFunctionCall - we use func_num_args only for args count matching here
2081
         */
2082 1
        if ($definition === null || \func_num_args() < 2) {
2083
            $a = \filter_input_array($type);
2084
        } else {
2085 1
            $a = \filter_input_array($type, $definition, $add_empty);
2086
        }
2087
2088 1
        return self::filter($a);
2089
    }
2090
2091
    /**
2092
     * "filter_var()"-wrapper with normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
2093
     *
2094
     * Filters a variable with a specified filter.
2095
     *
2096
     * EXAMPLE: <code>UTF8::filter_var('-ABC-中文空白-', FILTER_VALIDATE_URL); // false</code>
2097
     *
2098
     * @see http://php.net/manual/en/function.filter-var.php
2099
     *
2100
     * @param float|int|string|null $variable <p>
2101
     *                                        Value to filter.
2102
     *                                        </p>
2103
     * @param int                   $filter   [optional] <p>
2104
     *                                        The ID of the filter to apply. The
2105
     *                                        manual page lists the available filters.
2106
     *                                        </p>
2107
     * @param int|int[]|null        $options  [optional] <p>
2108
     *                                        Associative array of options or bitwise disjunction of flags. If filter
2109
     *                                        accepts options, flags can be provided in "flags" field of array. For
2110
     *                                        the "callback" filter, callable type should be passed. The
2111
     *                                        callback must accept one argument, the value to be filtered, and return
2112
     *                                        the value after filtering/sanitizing it.
2113
     *                                        </p>
2114
     *                                        <p>
2115
     *                                        <code>
2116
     *                                        // for filters that accept options, use this format
2117
     *                                        $options = array(
2118
     *                                        'options' => array(
2119
     *                                        'default' => 3, // value to return if the filter fails
2120
     *                                        // other options here
2121
     *                                        'min_range' => 0
2122
     *                                        ),
2123
     *                                        'flags' => FILTER_FLAG_ALLOW_OCTAL,
2124
     *                                        );
2125
     *                                        $var = filter_var('0755', FILTER_VALIDATE_INT, $options);
2126
     *                                        // for filter that only accept flags, you can pass them directly
2127
     *                                        $var = filter_var('oops', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
2128
     *                                        // for filter that only accept flags, you can also pass as an array
2129
     *                                        $var = filter_var('oops', FILTER_VALIDATE_BOOLEAN,
2130
     *                                        array('flags' => FILTER_NULL_ON_FAILURE));
2131
     *                                        // callback validate filter
2132
     *                                        function foo($value)
2133
     *                                        {
2134
     *                                        // Expected format: Surname, GivenNames
2135
     *                                        if (strpos($value, ", ") === false) return false;
2136
     *                                        list($surname, $givennames) = explode(", ", $value, 2);
2137
     *                                        $empty = (empty($surname) || empty($givennames));
2138
     *                                        $notstrings = (!is_string($surname) || !is_string($givennames));
2139
     *                                        if ($empty || $notstrings) {
2140
     *                                        return false;
2141
     *                                        } else {
2142
     *                                        return $value;
2143
     *                                        }
2144
     *                                        }
2145
     *                                        $var = filter_var('Doe, Jane Sue', FILTER_CALLBACK, array('options' => 'foo'));
2146
     *                                        </code>
2147
     *                                        </p>
2148
     *
2149
     * @psalm-pure
2150
     *
2151
     * @return mixed
2152
     *               <p>The filtered data, or <b>FALSE</b> if the filter fails.</p>
2153
     */
2154 2
    public static function filter_var(
2155
        $variable,
2156
        int $filter = \FILTER_DEFAULT,
2157
        $options = null
2158
    ) {
2159
        /**
2160
         * @psalm-suppress ImpureFunctionCall - we use func_num_args only for args count matching here
2161
         */
2162 2
        if (\func_num_args() < 3) {
2163 2
            $variable = \filter_var($variable, $filter);
2164
        } else {
2165 2
            $variable = \filter_var($variable, $filter, $options);
2166
        }
2167
2168 2
        return self::filter($variable);
2169
    }
2170
2171
    /**
2172
     * "filter_var_array()"-wrapper with normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
2173
     *
2174
     * Gets multiple variables and optionally filters them.
2175
     *
2176
     * EXAMPLE: <code>
2177
     * $filters = [
2178
     *     'name'  => ['filter'  => FILTER_CALLBACK, 'options' => [UTF8::class, 'ucwords']],
2179
     *     'age'   => ['filter'  => FILTER_VALIDATE_INT, 'options' => ['min_range' => 1, 'max_range' => 120]],
2180
     *     'email' => FILTER_VALIDATE_EMAIL,
2181
     * ];
2182
     *
2183
     * $data = [
2184
     *     'name' => 'κόσμε',
2185
     *     'age' => '18',
2186
     *     'email' => '[email protected]'
2187
     * ];
2188
     *
2189
     * UTF8::filter_var_array($data, $filters, true); // ['name' => 'Κόσμε', 'age' => 18, 'email' => '[email protected]']
2190
     * </code>
2191
     *
2192
     * @see http://php.net/manual/en/function.filter-var-array.php
2193
     *
2194
     * @param array<mixed>   $data       <p>
2195
     *                                   An array with string keys containing the data to filter.
2196
     *                                   </p>
2197
     * @param array|int|null $definition [optional] <p>
2198
     *                                   An array defining the arguments. A valid key is a string
2199
     *                                   containing a variable name and a valid value is either a
2200
     *                                   filter type, or an
2201
     *                                   array optionally specifying the filter, flags and options.
2202
     *                                   If the value is an array, valid keys are filter
2203
     *                                   which specifies the filter type,
2204
     *                                   flags which specifies any flags that apply to the
2205
     *                                   filter, and options which specifies any options that
2206
     *                                   apply to the filter. See the example below for a better understanding.
2207
     *                                   </p>
2208
     *                                   <p>
2209
     *                                   This parameter can be also an integer holding a filter constant. Then all values
2210
     *                                   in the input array are filtered by this filter.
2211
     *                                   </p>
2212
     * @param bool           $add_empty  [optional] <p>
2213
     *                                   Add missing keys as <b>NULL</b> to the return value.
2214
     *                                   </p>
2215
     *
2216
     * @psalm-pure
2217
     *
2218
     * @return mixed
2219
     *               <p>
2220
     *               An array containing the values of the requested variables on success, or <b>FALSE</b> on failure.
2221
     *               An array value will be <b>FALSE</b> if the filter fails, or <b>NULL</b> if the variable is not
2222
     *               set.
2223
     *               </p>
2224
     */
2225 2
    public static function filter_var_array(
2226
        array $data,
2227
        $definition = null,
2228
        bool $add_empty = true
2229
    ) {
2230
        /**
2231
         * @psalm-suppress ImpureFunctionCall - we use func_num_args only for args count matching here
2232
         */
2233 2
        if (\func_num_args() < 2) {
2234 2
            $a = \filter_var_array($data);
2235
        } else {
2236 2
            $a = \filter_var_array($data, $definition, $add_empty);
2237
        }
2238
2239 2
        return self::filter($a);
2240
    }
2241
2242
    /**
2243
     * Checks whether finfo is available on the server.
2244
     *
2245
     * @psalm-pure
2246
     *
2247
     * @return bool
2248
     *              <p><strong>true</strong> if available, <strong>false</strong> otherwise</p>
2249
     *
2250
     * @internal <p>Please do not use it anymore, we will make is private in next major version.</p>
2251
     */
2252
    public static function finfo_loaded(): bool
2253
    {
2254
        return \class_exists('finfo');
2255
    }
2256
2257
    /**
2258
     * Returns the first $n characters of the string.
2259
     *
2260
     * @param string $str      <p>The input string.</p>
2261
     * @param int    $n        <p>Number of characters to retrieve from the start.</p>
2262
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
2263
     *
2264
     * @psalm-pure
2265
     *
2266
     * @return string
2267
     */
2268 13
    public static function first_char(
2269
        string $str,
2270
        int $n = 1,
2271
        string $encoding = 'UTF-8'
2272
    ): string {
2273 13
        if ($str === '' || $n <= 0) {
2274 5
            return '';
2275
        }
2276
2277 8
        if ($encoding === 'UTF-8') {
2278 4
            return (string) \mb_substr($str, 0, $n);
2279
        }
2280
2281 4
        return (string) self::substr($str, 0, $n, $encoding);
2282
    }
2283
2284
    /**
2285
     * Check if the number of Unicode characters isn't greater than the specified integer.
2286
     *
2287
     * EXAMPLE: <code>UTF8::fits_inside('κόσμε', 6); // false</code>
2288
     *
2289
     * @param string $str      the original string to be checked
2290
     * @param int    $box_size the size in number of chars to be checked against string
2291
     *
2292
     * @psalm-pure
2293
     *
2294
     * @return bool
2295
     *              <p><strong>TRUE</strong> if string is less than or equal to $box_size, <strong>FALSE</strong> otherwise.</p>
2296
     */
2297 2
    public static function fits_inside(string $str, int $box_size): bool
2298
    {
2299 2
        return (int) self::strlen($str) <= $box_size;
2300
    }
2301
2302
    /**
2303
     * Try to fix simple broken UTF-8 strings.
2304
     *
2305
     * INFO: Take a look at "UTF8::fix_utf8()" if you need a more advanced fix for broken UTF-8 strings.
2306
     *
2307
     * EXAMPLE: <code>UTF8::fix_simple_utf8('Düsseldorf'); // 'Düsseldorf'</code>
2308
     *
2309
     * If you received an UTF-8 string that was converted from Windows-1252 as it was ISO-8859-1
2310
     * (ignoring Windows-1252 chars from 80 to 9F) use this function to fix it.
2311
     * See: http://en.wikipedia.org/wiki/Windows-1252
2312
     *
2313
     * @param string $str <p>The input string</p>
2314
     *
2315
     * @psalm-pure
2316
     *
2317
     * @return string
2318
     */
2319 47
    public static function fix_simple_utf8(string $str): string
2320
    {
2321 47
        if ($str === '') {
2322 4
            return '';
2323
        }
2324
2325
        /**
2326
         * @psalm-suppress ImpureStaticVariable
2327
         *
2328
         * @var array<mixed>|null
2329
         */
2330 47
        static $BROKEN_UTF8_TO_UTF8_KEYS_CACHE = null;
2331
2332
        /**
2333
         * @psalm-suppress ImpureStaticVariable
2334
         *
2335
         * @var array<mixed>|null
2336
         */
2337 47
        static $BROKEN_UTF8_TO_UTF8_VALUES_CACHE = null;
2338
2339 47
        if ($BROKEN_UTF8_TO_UTF8_KEYS_CACHE === null) {
2340 1
            if (self::$BROKEN_UTF8_FIX === null) {
2341 1
                self::$BROKEN_UTF8_FIX = self::getData('utf8_fix');
2342
            }
2343
2344 1
            $BROKEN_UTF8_TO_UTF8_KEYS_CACHE = \array_keys(self::$BROKEN_UTF8_FIX);
2345 1
            $BROKEN_UTF8_TO_UTF8_VALUES_CACHE = self::$BROKEN_UTF8_FIX;
2346
        }
2347
2348 47
        \assert(\is_array($BROKEN_UTF8_TO_UTF8_VALUES_CACHE));
2349
2350 47
        return \str_replace($BROKEN_UTF8_TO_UTF8_KEYS_CACHE, $BROKEN_UTF8_TO_UTF8_VALUES_CACHE, $str);
2351
    }
2352
2353
    /**
2354
     * Fix a double (or multiple) encoded UTF8 string.
2355
     *
2356
     * EXAMPLE: <code>UTF8::fix_utf8('Fédération'); // 'Fédération'</code>
2357
     *
2358
     * @param string|string[] $str you can use a string or an array of strings
2359
     *
2360
     * @psalm-pure
2361
     *
2362
     * @return string|string[]
2363
     *                         Will return the fixed input-"array" or
2364
     *                         the fixed input-"string"
2365
     *
2366
     * @psalm-suppress InvalidReturnType
2367
     */
2368 2
    public static function fix_utf8($str)
2369
    {
2370 2
        if (\is_array($str)) {
2371 2
            foreach ($str as $k => &$v) {
2372 2
                $v = self::fix_utf8($v);
2373
            }
2374 2
            unset($v);
2375
2376
            /**
2377
             * @psalm-suppress InvalidReturnStatement
2378
             */
2379 2
            return $str;
2380
        }
2381
2382 2
        $str = (string) $str;
2383 2
        $last = '';
2384 2
        while ($last !== $str) {
2385 2
            $last = $str;
2386
            /**
2387
             * @psalm-suppress PossiblyInvalidArgument
2388
             */
2389 2
            $str = self::to_utf8(
2390 2
                self::utf8_decode($str, true)
2391
            );
2392
        }
2393
2394
        /**
2395
         * @psalm-suppress InvalidReturnStatement
2396
         */
2397 2
        return $str;
2398
    }
2399
2400
    /**
2401
     * Get character of a specific character.
2402
     *
2403
     * EXAMPLE: <code>UTF8::getCharDirection('ا'); // 'RTL'</code>
2404
     *
2405
     * @param string $char
2406
     *
2407
     * @psalm-pure
2408
     *
2409
     * @return string
2410
     *                <p>'RTL' or 'LTR'.</p>
2411
     */
2412 2
    public static function getCharDirection(string $char): string
2413
    {
2414 2
        if (self::$SUPPORT['intlChar'] === true) {
2415
            /** @noinspection PhpComposerExtensionStubsInspection */
2416 2
            $tmp_return = \IntlChar::charDirection($char);
2417
2418
            // from "IntlChar"-Class
2419
            $char_direction = [
2420 2
                'RTL' => [1, 13, 14, 15, 21],
2421
                'LTR' => [0, 11, 12, 20],
2422
            ];
2423
2424 2
            if (\in_array($tmp_return, $char_direction['LTR'], true)) {
2425
                return 'LTR';
2426
            }
2427
2428 2
            if (\in_array($tmp_return, $char_direction['RTL'], true)) {
2429 2
                return 'RTL';
2430
            }
2431
        }
2432
2433 2
        $c = static::chr_to_decimal($char);
2434
2435 2
        if (!($c >= 0x5be && $c <= 0x10b7f)) {
2436 2
            return 'LTR';
2437
        }
2438
2439 2
        if ($c <= 0x85e) {
2440 2
            if ($c === 0x5be ||
2441 2
                $c === 0x5c0 ||
2442 2
                $c === 0x5c3 ||
2443 2
                $c === 0x5c6 ||
2444 2
                ($c >= 0x5d0 && $c <= 0x5ea) ||
2445 2
                ($c >= 0x5f0 && $c <= 0x5f4) ||
2446 2
                $c === 0x608 ||
2447 2
                $c === 0x60b ||
2448 2
                $c === 0x60d ||
2449 2
                $c === 0x61b ||
2450 2
                ($c >= 0x61e && $c <= 0x64a) ||
2451
                ($c >= 0x66d && $c <= 0x66f) ||
2452
                ($c >= 0x671 && $c <= 0x6d5) ||
2453
                ($c >= 0x6e5 && $c <= 0x6e6) ||
2454
                ($c >= 0x6ee && $c <= 0x6ef) ||
2455
                ($c >= 0x6fa && $c <= 0x70d) ||
2456
                $c === 0x710 ||
2457
                ($c >= 0x712 && $c <= 0x72f) ||
2458
                ($c >= 0x74d && $c <= 0x7a5) ||
2459
                $c === 0x7b1 ||
2460
                ($c >= 0x7c0 && $c <= 0x7ea) ||
2461
                ($c >= 0x7f4 && $c <= 0x7f5) ||
2462
                $c === 0x7fa ||
2463
                ($c >= 0x800 && $c <= 0x815) ||
2464
                $c === 0x81a ||
2465
                $c === 0x824 ||
2466
                $c === 0x828 ||
2467
                ($c >= 0x830 && $c <= 0x83e) ||
2468
                ($c >= 0x840 && $c <= 0x858) ||
2469 2
                $c === 0x85e
2470
            ) {
2471 2
                return 'RTL';
2472
            }
2473 2
        } elseif ($c === 0x200f) {
2474
            return 'RTL';
2475 2
        } elseif ($c >= 0xfb1d) {
2476 2
            if ($c === 0xfb1d ||
2477 2
                ($c >= 0xfb1f && $c <= 0xfb28) ||
2478 2
                ($c >= 0xfb2a && $c <= 0xfb36) ||
2479 2
                ($c >= 0xfb38 && $c <= 0xfb3c) ||
2480 2
                $c === 0xfb3e ||
2481 2
                ($c >= 0xfb40 && $c <= 0xfb41) ||
2482 2
                ($c >= 0xfb43 && $c <= 0xfb44) ||
2483 2
                ($c >= 0xfb46 && $c <= 0xfbc1) ||
2484 2
                ($c >= 0xfbd3 && $c <= 0xfd3d) ||
2485 2
                ($c >= 0xfd50 && $c <= 0xfd8f) ||
2486 2
                ($c >= 0xfd92 && $c <= 0xfdc7) ||
2487 2
                ($c >= 0xfdf0 && $c <= 0xfdfc) ||
2488 2
                ($c >= 0xfe70 && $c <= 0xfe74) ||
2489 2
                ($c >= 0xfe76 && $c <= 0xfefc) ||
2490 2
                ($c >= 0x10800 && $c <= 0x10805) ||
2491 2
                $c === 0x10808 ||
2492 2
                ($c >= 0x1080a && $c <= 0x10835) ||
2493 2
                ($c >= 0x10837 && $c <= 0x10838) ||
2494 2
                $c === 0x1083c ||
2495 2
                ($c >= 0x1083f && $c <= 0x10855) ||
2496 2
                ($c >= 0x10857 && $c <= 0x1085f) ||
2497 2
                ($c >= 0x10900 && $c <= 0x1091b) ||
2498 2
                ($c >= 0x10920 && $c <= 0x10939) ||
2499 2
                $c === 0x1093f ||
2500 2
                $c === 0x10a00 ||
2501 2
                ($c >= 0x10a10 && $c <= 0x10a13) ||
2502 2
                ($c >= 0x10a15 && $c <= 0x10a17) ||
2503 2
                ($c >= 0x10a19 && $c <= 0x10a33) ||
2504 2
                ($c >= 0x10a40 && $c <= 0x10a47) ||
2505 2
                ($c >= 0x10a50 && $c <= 0x10a58) ||
2506 2
                ($c >= 0x10a60 && $c <= 0x10a7f) ||
2507 2
                ($c >= 0x10b00 && $c <= 0x10b35) ||
2508 2
                ($c >= 0x10b40 && $c <= 0x10b55) ||
2509 2
                ($c >= 0x10b58 && $c <= 0x10b72) ||
2510 2
                ($c >= 0x10b78 && $c <= 0x10b7f)
2511
            ) {
2512 2
                return 'RTL';
2513
            }
2514
        }
2515
2516 2
        return 'LTR';
2517
    }
2518
2519
    /**
2520
     * Check for php-support.
2521
     *
2522
     * @param string|null $key
2523
     *
2524
     * @psalm-pure
2525
     *
2526
     * @return mixed
2527
     *               Return the full support-"array", if $key === null<br>
2528
     *               return bool-value, if $key is used and available<br>
2529
     *               otherwise return <strong>null</strong>
2530
     */
2531 27
    public static function getSupportInfo(string $key = null)
2532
    {
2533 27
        if ($key === null) {
2534 4
            return self::$SUPPORT;
2535
        }
2536
2537 25
        if (self::$INTL_TRANSLITERATOR_LIST === null) {
2538 1
            self::$INTL_TRANSLITERATOR_LIST = self::getData('transliterator_list');
2539
        }
2540
        // compatibility fix for old versions
2541 25
        self::$SUPPORT['intl__transliterator_list_ids'] = self::$INTL_TRANSLITERATOR_LIST;
2542
2543 25
        return self::$SUPPORT[$key] ?? null;
2544
    }
2545
2546
    /**
2547
     * Warning: this method only works for some file-types (png, jpg)
2548
     *          if you need more supported types, please use e.g. "finfo"
2549
     *
2550
     * @param string $str
2551
     * @param array  $fallback <p>with this keys: 'ext', 'mime', 'type'
2552
     *
2553
     * @psalm-pure
2554
     *
2555
     * @return null[]|string[]
2556
     *                         <p>with this keys: 'ext', 'mime', 'type'</p>
2557
     *
2558
     * @phpstan-param array{ext: null|string, mime: null|string, type: null|string} $fallback
2559
     */
2560 40
    public static function get_file_type(
2561
        string $str,
2562
        array $fallback = [
2563
            'ext'  => null,
2564
            'mime' => 'application/octet-stream',
2565
            'type' => null,
2566
        ]
2567
    ): array {
2568 40
        if ($str === '') {
2569
            return $fallback;
2570
        }
2571
2572
        /** @var false|string $str_info - needed for PhpStan (stubs error) */
2573 40
        $str_info = \substr($str, 0, 2);
2574 40
        if ($str_info === false || \strlen($str_info) !== 2) {
2575 11
            return $fallback;
2576
        }
2577
2578
        // DEBUG
2579
        //var_dump($str_info);
2580
2581 36
        $str_info = \unpack('C2chars', $str_info);
2582
2583
        /** @noinspection PhpSillyAssignmentInspection */
2584
        /** @var array|false $str_info - needed for PhpStan (stubs error) */
2585 36
        $str_info = $str_info;
2586
2587 36
        if ($str_info === false) {
2588
            return $fallback;
2589
        }
2590
        /** @noinspection OffsetOperationsInspection */
2591 36
        $type_code = (int) ($str_info['chars1'] . $str_info['chars2']);
2592
2593
        // DEBUG
2594
        //var_dump($type_code);
2595
2596
        //
2597
        // info: https://en.wikipedia.org/wiki/Magic_number_%28programming%29#Format_indicator
2598
        //
2599
        switch ($type_code) {
2600
            // WARNING: do not add too simple comparisons, because of false-positive results:
2601
            //
2602
            // 3780 => 'pdf', 7790 => 'exe', 7784 => 'midi', 8075 => 'zip',
2603
            // 8297 => 'rar', 7173 => 'gif', 7373 => 'tiff' 6677 => 'bmp', ...
2604
            //
2605 36
            case 255216:
2606
                $ext = 'jpg';
2607
                $mime = 'image/jpeg';
2608
                $type = 'binary';
2609
2610
                break;
2611 36
            case 13780:
2612 7
                $ext = 'png';
2613 7
                $mime = 'image/png';
2614 7
                $type = 'binary';
2615
2616 7
                break;
2617
            default:
2618 35
                return $fallback;
2619
        }
2620
2621
        return [
2622 7
            'ext'  => $ext,
2623 7
            'mime' => $mime,
2624 7
            'type' => $type,
2625
        ];
2626
    }
2627
2628
    /**
2629
     * @param int    $length         <p>Length of the random string.</p>
2630
     * @param string $possible_chars [optional] <p>Characters string for the random selection.</p>
2631
     * @param string $encoding       [optional] <p>Set the charset for e.g. "mb_" function</p>
2632
     *
2633
     * @return string
2634
     */
2635 1
    public static function get_random_string(
2636
        int $length,
2637
        string $possible_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
2638
        string $encoding = 'UTF-8'
2639
    ): string {
2640
        // init
2641 1
        $i = 0;
2642 1
        $str = '';
2643
2644
        //
2645
        // add random chars
2646
        //
2647
2648 1
        if ($encoding === 'UTF-8') {
2649 1
            $max_length = (int) \mb_strlen($possible_chars);
2650 1
            if ($max_length === 0) {
2651 1
                return '';
2652
            }
2653
2654 1
            while ($i < $length) {
2655
                try {
2656 1
                    $rand_int = \random_int(0, $max_length - 1);
2657
                } catch (\Exception $e) {
2658
                    /** @noinspection RandomApiMigrationInspection */
2659
                    $rand_int = \mt_rand(0, $max_length - 1);
2660
                }
2661 1
                $char = \mb_substr($possible_chars, $rand_int, 1);
2662 1
                if ($char !== false) {
2663 1
                    $str .= $char;
2664 1
                    ++$i;
2665
                }
2666
            }
2667
        } else {
2668
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
2669
2670
            $max_length = (int) self::strlen($possible_chars, $encoding);
2671
            if ($max_length === 0) {
2672
                return '';
2673
            }
2674
2675
            while ($i < $length) {
2676
                try {
2677
                    $rand_int = \random_int(0, $max_length - 1);
2678
                } catch (\Exception $e) {
2679
                    /** @noinspection RandomApiMigrationInspection */
2680
                    $rand_int = \mt_rand(0, $max_length - 1);
2681
                }
2682
                $char = self::substr($possible_chars, $rand_int, 1, $encoding);
2683
                if ($char !== false) {
2684
                    $str .= $char;
2685
                    ++$i;
2686
                }
2687
            }
2688
        }
2689
2690 1
        return $str;
2691
    }
2692
2693
    /**
2694
     * @param int|string $extra_entropy [optional] <p>Extra entropy via a string or int value.</p>
2695
     * @param bool       $use_md5       [optional] <p>Return the unique identifier as md5-hash? Default: true</p>
2696
     *
2697
     * @return string
2698
     */
2699 1
    public static function get_unique_string($extra_entropy = '', bool $use_md5 = true): string
2700
    {
2701
        try {
2702 1
            $rand_int = \random_int(0, \mt_getrandmax());
2703
        } catch (\Exception $e) {
2704
            /** @noinspection RandomApiMigrationInspection */
2705
            $rand_int = \mt_rand(0, \mt_getrandmax());
2706
        }
2707
2708
        $unique_helper = $rand_int .
2709 1
                         \session_id() .
2710 1
                         ($_SERVER['REMOTE_ADDR'] ?? '') .
2711 1
                         ($_SERVER['SERVER_ADDR'] ?? '') .
2712 1
                         $extra_entropy;
2713
2714 1
        $unique_string = \uniqid($unique_helper, true);
2715
2716 1
        if ($use_md5) {
2717 1
            $unique_string = \md5($unique_string . $unique_helper);
2718
        }
2719
2720 1
        return $unique_string;
2721
    }
2722
2723
    /**
2724
     * alias for "UTF8::string_has_bom()"
2725
     *
2726
     * @param string $str
2727
     *
2728
     * @psalm-pure
2729
     *
2730
     * @return bool
2731
     *
2732
     * @see        UTF8::string_has_bom()
2733
     * @deprecated <p>please use "UTF8::string_has_bom()"</p>
2734
     */
2735 2
    public static function hasBom(string $str): bool
2736
    {
2737 2
        return self::string_has_bom($str);
2738
    }
2739
2740
    /**
2741
     * Returns true if the string contains a lower case char, false otherwise.
2742
     *
2743
     * @param string $str <p>The input string.</p>
2744
     *
2745
     * @psalm-pure
2746
     *
2747
     * @return bool
2748
     *              <p>Whether or not the string contains a lower case character.</p>
2749
     */
2750 47
    public static function has_lowercase(string $str): bool
2751
    {
2752 47
        if (self::$SUPPORT['mbstring'] === true) {
2753
            /** @noinspection PhpComposerExtensionStubsInspection */
2754 47
            return \mb_ereg_match('.*[[:lower:]]', $str);
2755
        }
2756
2757
        return self::str_matches_pattern($str, '.*[[:lower:]]');
2758
    }
2759
2760
    /**
2761
     * Returns true if the string contains whitespace, false otherwise.
2762
     *
2763
     * @param string $str <p>The input string.</p>
2764
     *
2765
     * @psalm-pure
2766
     *
2767
     * @return bool
2768
     *              <p>Whether or not the string contains whitespace.</p>
2769
     */
2770 11
    public static function has_whitespace(string $str): bool
2771
    {
2772 11
        if (self::$SUPPORT['mbstring'] === true) {
2773
            /** @noinspection PhpComposerExtensionStubsInspection */
2774 11
            return \mb_ereg_match('.*[[:space:]]', $str);
2775
        }
2776
2777
        return self::str_matches_pattern($str, '.*[[:space:]]');
2778
    }
2779
2780
    /**
2781
     * Returns true if the string contains an upper case char, false otherwise.
2782
     *
2783
     * @param string $str <p>The input string.</p>
2784
     *
2785
     * @psalm-pure
2786
     *
2787
     * @return bool
2788
     *              <p>Whether or not the string contains an upper case character.</p>
2789
     */
2790 12
    public static function has_uppercase(string $str): bool
2791
    {
2792 12
        if (self::$SUPPORT['mbstring'] === true) {
2793
            /** @noinspection PhpComposerExtensionStubsInspection */
2794 12
            return \mb_ereg_match('.*[[:upper:]]', $str);
2795
        }
2796
2797
        return self::str_matches_pattern($str, '.*[[:upper:]]');
2798
    }
2799
2800
    /**
2801
     * Converts a hexadecimal value into a UTF-8 character.
2802
     *
2803
     * INFO: opposite to UTF8::chr_to_hex()
2804
     *
2805
     * EXAMPLE: <code>UTF8::hex_to_chr('U+00a7'); // '§'</code>
2806
     *
2807
     * @param string $hexdec <p>The hexadecimal value.</p>
2808
     *
2809
     * @psalm-pure
2810
     *
2811
     * @return false|string one single UTF-8 character
2812
     */
2813 4
    public static function hex_to_chr(string $hexdec)
2814
    {
2815
        /** @noinspection PhpUsageOfSilenceOperatorInspection - Invalid characters passed for attempted conversion, these have been ignored */
2816 4
        return self::decimal_to_chr((int) @\hexdec($hexdec));
2817
    }
2818
2819
    /**
2820
     * Converts hexadecimal U+xxxx code point representation to integer.
2821
     *
2822
     * INFO: opposite to UTF8::int_to_hex()
2823
     *
2824
     * EXAMPLE: <code>UTF8::hex_to_int('U+00f1'); // 241</code>
2825
     *
2826
     * @param string $hexdec <p>The hexadecimal code point representation.</p>
2827
     *
2828
     * @psalm-pure
2829
     *
2830
     * @return false|int
2831
     *                   <p>The code point, or false on failure.</p>
2832
     */
2833 2
    public static function hex_to_int($hexdec)
2834
    {
2835
        // init
2836 2
        $hexdec = (string) $hexdec;
2837
2838 2
        if ($hexdec === '') {
2839 2
            return false;
2840
        }
2841
2842 2
        if (\preg_match('/^(?:\\\u|U\+|)([a-zA-Z0-9]{4,6})$/', $hexdec, $match)) {
2843 2
            return \intval($match[1], 16);
2844
        }
2845
2846 2
        return false;
2847
    }
2848
2849
    /**
2850
     * alias for "UTF8::html_entity_decode()"
2851
     *
2852
     * @param string   $str
2853
     * @param int|null $flags
2854
     * @param string   $encoding
2855
     *
2856
     * @psalm-pure
2857
     *
2858
     * @return string
2859
     *
2860
     * @see        UTF8::html_entity_decode()
2861
     * @deprecated <p>please use "UTF8::html_entity_decode()"</p>
2862
     */
2863 2
    public static function html_decode(
2864
        string $str,
2865
        int $flags = null,
2866
        string $encoding = 'UTF-8'
2867
    ): string {
2868 2
        return self::html_entity_decode($str, $flags, $encoding);
2869
    }
2870
2871
    /**
2872
     * Converts a UTF-8 string to a series of HTML numbered entities.
2873
     *
2874
     * INFO: opposite to UTF8::html_decode()
2875
     *
2876
     * EXAMPLE: <code>UTF8::html_encode('中文空白'); // '&#20013;&#25991;&#31354;&#30333;'</code>
2877
     *
2878
     * @param string $str              <p>The Unicode string to be encoded as numbered entities.</p>
2879
     * @param bool   $keep_ascii_chars [optional] <p>Keep ASCII chars.</p>
2880
     * @param string $encoding         [optional] <p>Set the charset for e.g. "mb_" function</p>
2881
     *
2882
     * @psalm-pure
2883
     *
2884
     * @return string HTML numbered entities
2885
     */
2886 14
    public static function html_encode(
2887
        string $str,
2888
        bool $keep_ascii_chars = false,
2889
        string $encoding = 'UTF-8'
2890
    ): string {
2891 14
        if ($str === '') {
2892 4
            return '';
2893
        }
2894
2895 14
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
2896 4
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
2897
        }
2898
2899
        // INFO: http://stackoverflow.com/questions/35854535/better-explanation-of-convmap-in-mb-encode-numericentity
2900 14
        if (self::$SUPPORT['mbstring'] === true) {
2901 14
            if ($keep_ascii_chars) {
2902 13
                $start_code = 0x80;
2903
            } else {
2904 3
                $start_code = 0x00;
2905
            }
2906
2907 14
            if ($encoding === 'UTF-8') {
2908
                /** @var false|string|null $return - needed for PhpStan (stubs error) */
2909 14
                $return = \mb_encode_numericentity(
2910 14
                    $str,
2911 14
                    [$start_code, 0xfffff, 0, 0xfffff]
2912
                );
2913 14
                if ($return !== null && $return !== false) {
2914 14
                    return $return;
2915
                }
2916
            }
2917
2918
            /** @var false|string|null $return - needed for PhpStan (stubs error) */
2919 4
            $return = \mb_encode_numericentity(
2920 4
                $str,
2921 4
                [$start_code, 0xfffff, 0, 0xfffff],
2922 4
                $encoding
2923
            );
2924 4
            if ($return !== null && $return !== false) {
2925 4
                return $return;
2926
            }
2927
        }
2928
2929
        //
2930
        // fallback via vanilla php
2931
        //
2932
2933
        return \implode(
2934
            '',
2935
            \array_map(
2936
                static function (string $chr) use ($keep_ascii_chars, $encoding): string {
2937
                    return self::single_chr_html_encode($chr, $keep_ascii_chars, $encoding);
2938
                },
2939
                self::str_split($str)
2940
            )
2941
        );
2942
    }
2943
2944
    /**
2945
     * UTF-8 version of html_entity_decode()
2946
     *
2947
     * The reason we are not using html_entity_decode() by itself is because
2948
     * while it is not technically correct to leave out the semicolon
2949
     * at the end of an entity most browsers will still interpret the entity
2950
     * correctly. html_entity_decode() does not convert entities without
2951
     * semicolons, so we are left with our own little solution here. Bummer.
2952
     *
2953
     * Convert all HTML entities to their applicable characters.
2954
     *
2955
     * INFO: opposite to UTF8::html_encode()
2956
     *
2957
     * EXAMPLE: <code>UTF8::html_entity_decode('&#20013;&#25991;&#31354;&#30333;'); // '中文空白'</code>
2958
     *
2959
     * @see http://php.net/manual/en/function.html-entity-decode.php
2960
     *
2961
     * @param string   $str      <p>
2962
     *                           The input string.
2963
     *                           </p>
2964
     * @param int|null $flags    [optional] <p>
2965
     *                           A bitmask of one or more of the following flags, which specify how to handle quotes
2966
     *                           and which document type to use. The default is ENT_COMPAT | ENT_HTML401.
2967
     *                           <table>
2968
     *                           Available <i>flags</i> constants
2969
     *                           <tr valign="top">
2970
     *                           <td>Constant Name</td>
2971
     *                           <td>Description</td>
2972
     *                           </tr>
2973
     *                           <tr valign="top">
2974
     *                           <td><b>ENT_COMPAT</b></td>
2975
     *                           <td>Will convert double-quotes and leave single-quotes alone.</td>
2976
     *                           </tr>
2977
     *                           <tr valign="top">
2978
     *                           <td><b>ENT_QUOTES</b></td>
2979
     *                           <td>Will convert both double and single quotes.</td>
2980
     *                           </tr>
2981
     *                           <tr valign="top">
2982
     *                           <td><b>ENT_NOQUOTES</b></td>
2983
     *                           <td>Will leave both double and single quotes unconverted.</td>
2984
     *                           </tr>
2985
     *                           <tr valign="top">
2986
     *                           <td><b>ENT_HTML401</b></td>
2987
     *                           <td>
2988
     *                           Handle code as HTML 4.01.
2989
     *                           </td>
2990
     *                           </tr>
2991
     *                           <tr valign="top">
2992
     *                           <td><b>ENT_XML1</b></td>
2993
     *                           <td>
2994
     *                           Handle code as XML 1.
2995
     *                           </td>
2996
     *                           </tr>
2997
     *                           <tr valign="top">
2998
     *                           <td><b>ENT_XHTML</b></td>
2999
     *                           <td>
3000
     *                           Handle code as XHTML.
3001
     *                           </td>
3002
     *                           </tr>
3003
     *                           <tr valign="top">
3004
     *                           <td><b>ENT_HTML5</b></td>
3005
     *                           <td>
3006
     *                           Handle code as HTML 5.
3007
     *                           </td>
3008
     *                           </tr>
3009
     *                           </table>
3010
     *                           </p>
3011
     * @param string   $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
3012
     *
3013
     * @psalm-pure
3014
     *
3015
     * @return string the decoded string
3016
     */
3017 51
    public static function html_entity_decode(
3018
        string $str,
3019
        int $flags = null,
3020
        string $encoding = 'UTF-8'
3021
    ): string {
3022
        if (
3023 51
            !isset($str[3]) // examples: &; || &x;
3024
            ||
3025 51
            \strpos($str, '&') === false // no "&"
3026
        ) {
3027 24
            return $str;
3028
        }
3029
3030 49
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
3031 9
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
3032
        }
3033
3034 49
        if ($flags === null) {
3035 11
            $flags = \ENT_QUOTES | \ENT_HTML5;
3036
        }
3037
3038
        /** @noinspection InArrayCanBeUsedInspection */
3039
        if (
3040 49
            $encoding !== 'UTF-8'
3041
            &&
3042 49
            $encoding !== 'ISO-8859-1'
3043
            &&
3044 49
            $encoding !== 'WINDOWS-1252'
3045
            &&
3046 49
            self::$SUPPORT['mbstring'] === false
3047
        ) {
3048
            /**
3049
             * @psalm-suppress ImpureFunctionCall - is is only a warning
3050
             */
3051
            \trigger_error('UTF8::html_entity_decode() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
3052
        }
3053
3054
        do {
3055 49
            $str_compare = $str;
3056
3057 49
            if (\strpos($str, '&') !== false) {
3058 49
                if (\strpos($str, '&#') !== false) {
3059
                    // decode also numeric & UTF16 two byte entities
3060 41
                    $str = (string) \preg_replace(
3061 41
                        '/(&#(?:x0*[0-9a-fA-F]{2,6}(?![0-9a-fA-F;])|(?:0*\d{2,6}(?![0-9;]))))/S',
3062 41
                        '$1;',
3063 41
                        $str
3064
                    );
3065
                }
3066
3067 49
                $str = \html_entity_decode(
3068 49
                    $str,
3069 49
                    $flags,
3070 49
                    $encoding
3071
                );
3072
            }
3073 49
        } while ($str_compare !== $str);
3074
3075 49
        return $str;
3076
    }
3077
3078
    /**
3079
     * Create a escape html version of the string via "UTF8::htmlspecialchars()".
3080
     *
3081
     * @param string $str
3082
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
3083
     *
3084
     * @psalm-pure
3085
     *
3086
     * @return string
3087
     */
3088 6
    public static function html_escape(string $str, string $encoding = 'UTF-8'): string
3089
    {
3090 6
        return self::htmlspecialchars(
3091 6
            $str,
3092 6
            \ENT_QUOTES | \ENT_SUBSTITUTE,
3093 6
            $encoding
3094
        );
3095
    }
3096
3097
    /**
3098
     * Remove empty html-tag.
3099
     *
3100
     * e.g.: <pre><tag></tag></pre>
3101
     *
3102
     * @param string $str
3103
     *
3104
     * @psalm-pure
3105
     *
3106
     * @return string
3107
     */
3108 1
    public static function html_stripe_empty_tags(string $str): string
3109
    {
3110 1
        return (string) \preg_replace(
3111 1
            '/<[^\\/>]*?>\\s*?<\\/[^>]*?>/u',
3112 1
            '',
3113 1
            $str
3114
        );
3115
    }
3116
3117
    /**
3118
     * Convert all applicable characters to HTML entities: UTF-8 version of htmlentities().
3119
     *
3120
     * EXAMPLE: <code>UTF8::htmlentities('<白-öäü>'); // '&lt;&#30333;-&ouml;&auml;&uuml;&gt;'</code>
3121
     *
3122
     * @see http://php.net/manual/en/function.htmlentities.php
3123
     *
3124
     * @param string $str           <p>
3125
     *                              The input string.
3126
     *                              </p>
3127
     * @param int    $flags         [optional] <p>
3128
     *                              A bitmask of one or more of the following flags, which specify how to handle
3129
     *                              quotes, invalid code unit sequences and the used document type. The default is
3130
     *                              ENT_COMPAT | ENT_HTML401.
3131
     *                              <table>
3132
     *                              Available <i>flags</i> constants
3133
     *                              <tr valign="top">
3134
     *                              <td>Constant Name</td>
3135
     *                              <td>Description</td>
3136
     *                              </tr>
3137
     *                              <tr valign="top">
3138
     *                              <td><b>ENT_COMPAT</b></td>
3139
     *                              <td>Will convert double-quotes and leave single-quotes alone.</td>
3140
     *                              </tr>
3141
     *                              <tr valign="top">
3142
     *                              <td><b>ENT_QUOTES</b></td>
3143
     *                              <td>Will convert both double and single quotes.</td>
3144
     *                              </tr>
3145
     *                              <tr valign="top">
3146
     *                              <td><b>ENT_NOQUOTES</b></td>
3147
     *                              <td>Will leave both double and single quotes unconverted.</td>
3148
     *                              </tr>
3149
     *                              <tr valign="top">
3150
     *                              <td><b>ENT_IGNORE</b></td>
3151
     *                              <td>
3152
     *                              Silently discard invalid code unit sequences instead of returning
3153
     *                              an empty string. Using this flag is discouraged as it
3154
     *                              may have security implications.
3155
     *                              </td>
3156
     *                              </tr>
3157
     *                              <tr valign="top">
3158
     *                              <td><b>ENT_SUBSTITUTE</b></td>
3159
     *                              <td>
3160
     *                              Replace invalid code unit sequences with a Unicode Replacement Character
3161
     *                              U+FFFD (UTF-8) or &#38;#38;#FFFD; (otherwise) instead of returning an empty
3162
     *                              string.
3163
     *                              </td>
3164
     *                              </tr>
3165
     *                              <tr valign="top">
3166
     *                              <td><b>ENT_DISALLOWED</b></td>
3167
     *                              <td>
3168
     *                              Replace invalid code points for the given document type with a
3169
     *                              Unicode Replacement Character U+FFFD (UTF-8) or &#38;#38;#FFFD;
3170
     *                              (otherwise) instead of leaving them as is. This may be useful, for
3171
     *                              instance, to ensure the well-formedness of XML documents with
3172
     *                              embedded external content.
3173
     *                              </td>
3174
     *                              </tr>
3175
     *                              <tr valign="top">
3176
     *                              <td><b>ENT_HTML401</b></td>
3177
     *                              <td>
3178
     *                              Handle code as HTML 4.01.
3179
     *                              </td>
3180
     *                              </tr>
3181
     *                              <tr valign="top">
3182
     *                              <td><b>ENT_XML1</b></td>
3183
     *                              <td>
3184
     *                              Handle code as XML 1.
3185
     *                              </td>
3186
     *                              </tr>
3187
     *                              <tr valign="top">
3188
     *                              <td><b>ENT_XHTML</b></td>
3189
     *                              <td>
3190
     *                              Handle code as XHTML.
3191
     *                              </td>
3192
     *                              </tr>
3193
     *                              <tr valign="top">
3194
     *                              <td><b>ENT_HTML5</b></td>
3195
     *                              <td>
3196
     *                              Handle code as HTML 5.
3197
     *                              </td>
3198
     *                              </tr>
3199
     *                              </table>
3200
     *                              </p>
3201
     * @param string $encoding      [optional] <p>
3202
     *                              Like <b>htmlspecialchars</b>,
3203
     *                              <b>htmlentities</b> takes an optional third argument
3204
     *                              <i>encoding</i> which defines encoding used in
3205
     *                              conversion.
3206
     *                              Although this argument is technically optional, you are highly
3207
     *                              encouraged to specify the correct value for your code.
3208
     *                              </p>
3209
     * @param bool   $double_encode [optional] <p>
3210
     *                              When <i>double_encode</i> is turned off PHP will not
3211
     *                              encode existing html entities. The default is to convert everything.
3212
     *                              </p>
3213
     *
3214
     * @psalm-pure
3215
     *
3216
     * @return string
3217
     *                <p>
3218
     *                The encoded string.
3219
     *                <br><br>
3220
     *                If the input <i>string</i> contains an invalid code unit
3221
     *                sequence within the given <i>encoding</i> an empty string
3222
     *                will be returned, unless either the <b>ENT_IGNORE</b> or
3223
     *                <b>ENT_SUBSTITUTE</b> flags are set.
3224
     *                </p>
3225
     */
3226 9
    public static function htmlentities(
3227
        string $str,
3228
        int $flags = \ENT_COMPAT,
3229
        string $encoding = 'UTF-8',
3230
        bool $double_encode = true
3231
    ): string {
3232 9
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
3233 7
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
3234
        }
3235
3236 9
        $str = \htmlentities(
3237 9
            $str,
3238 9
            $flags,
3239 9
            $encoding,
3240 9
            $double_encode
3241
        );
3242
3243
        /**
3244
         * PHP doesn't replace a backslash to its html entity since this is something
3245
         * that's mostly used to escape characters when inserting in a database. Since
3246
         * we're using a decent database layer, we don't need this shit and we're replacing
3247
         * the double backslashes by its' html entity equivalent.
3248
         *
3249
         * https://github.com/forkcms/library/blob/master/spoon/filter/filter.php#L303
3250
         */
3251 9
        $str = \str_replace('\\', '&#92;', $str);
3252
3253 9
        return self::html_encode($str, true, $encoding);
3254
    }
3255
3256
    /**
3257
     * Convert only special characters to HTML entities: UTF-8 version of htmlspecialchars()
3258
     *
3259
     * INFO: Take a look at "UTF8::htmlentities()"
3260
     *
3261
     * EXAMPLE: <code>UTF8::htmlspecialchars('<白-öäü>'); // '&lt;白-öäü&gt;'</code>
3262
     *
3263
     * @see http://php.net/manual/en/function.htmlspecialchars.php
3264
     *
3265
     * @param string $str           <p>
3266
     *                              The string being converted.
3267
     *                              </p>
3268
     * @param int    $flags         [optional] <p>
3269
     *                              A bitmask of one or more of the following flags, which specify how to handle
3270
     *                              quotes, invalid code unit sequences and the used document type. The default is
3271
     *                              ENT_COMPAT | ENT_HTML401.
3272
     *                              <table>
3273
     *                              Available <i>flags</i> constants
3274
     *                              <tr valign="top">
3275
     *                              <td>Constant Name</td>
3276
     *                              <td>Description</td>
3277
     *                              </tr>
3278
     *                              <tr valign="top">
3279
     *                              <td><b>ENT_COMPAT</b></td>
3280
     *                              <td>Will convert double-quotes and leave single-quotes alone.</td>
3281
     *                              </tr>
3282
     *                              <tr valign="top">
3283
     *                              <td><b>ENT_QUOTES</b></td>
3284
     *                              <td>Will convert both double and single quotes.</td>
3285
     *                              </tr>
3286
     *                              <tr valign="top">
3287
     *                              <td><b>ENT_NOQUOTES</b></td>
3288
     *                              <td>Will leave both double and single quotes unconverted.</td>
3289
     *                              </tr>
3290
     *                              <tr valign="top">
3291
     *                              <td><b>ENT_IGNORE</b></td>
3292
     *                              <td>
3293
     *                              Silently discard invalid code unit sequences instead of returning
3294
     *                              an empty string. Using this flag is discouraged as it
3295
     *                              may have security implications.
3296
     *                              </td>
3297
     *                              </tr>
3298
     *                              <tr valign="top">
3299
     *                              <td><b>ENT_SUBSTITUTE</b></td>
3300
     *                              <td>
3301
     *                              Replace invalid code unit sequences with a Unicode Replacement Character
3302
     *                              U+FFFD (UTF-8) or &#38;#38;#FFFD; (otherwise) instead of returning an empty
3303
     *                              string.
3304
     *                              </td>
3305
     *                              </tr>
3306
     *                              <tr valign="top">
3307
     *                              <td><b>ENT_DISALLOWED</b></td>
3308
     *                              <td>
3309
     *                              Replace invalid code points for the given document type with a
3310
     *                              Unicode Replacement Character U+FFFD (UTF-8) or &#38;#38;#FFFD;
3311
     *                              (otherwise) instead of leaving them as is. This may be useful, for
3312
     *                              instance, to ensure the well-formedness of XML documents with
3313
     *                              embedded external content.
3314
     *                              </td>
3315
     *                              </tr>
3316
     *                              <tr valign="top">
3317
     *                              <td><b>ENT_HTML401</b></td>
3318
     *                              <td>
3319
     *                              Handle code as HTML 4.01.
3320
     *                              </td>
3321
     *                              </tr>
3322
     *                              <tr valign="top">
3323
     *                              <td><b>ENT_XML1</b></td>
3324
     *                              <td>
3325
     *                              Handle code as XML 1.
3326
     *                              </td>
3327
     *                              </tr>
3328
     *                              <tr valign="top">
3329
     *                              <td><b>ENT_XHTML</b></td>
3330
     *                              <td>
3331
     *                              Handle code as XHTML.
3332
     *                              </td>
3333
     *                              </tr>
3334
     *                              <tr valign="top">
3335
     *                              <td><b>ENT_HTML5</b></td>
3336
     *                              <td>
3337
     *                              Handle code as HTML 5.
3338
     *                              </td>
3339
     *                              </tr>
3340
     *                              </table>
3341
     *                              </p>
3342
     * @param string $encoding      [optional] <p>
3343
     *                              Defines encoding used in conversion.
3344
     *                              </p>
3345
     *                              <p>
3346
     *                              For the purposes of this function, the encodings
3347
     *                              ISO-8859-1, ISO-8859-15,
3348
     *                              UTF-8, cp866,
3349
     *                              cp1251, cp1252, and
3350
     *                              KOI8-R are effectively equivalent, provided the
3351
     *                              <i>string</i> itself is valid for the encoding, as
3352
     *                              the characters affected by <b>htmlspecialchars</b> occupy
3353
     *                              the same positions in all of these encodings.
3354
     *                              </p>
3355
     * @param bool   $double_encode [optional] <p>
3356
     *                              When <i>double_encode</i> is turned off PHP will not
3357
     *                              encode existing html entities, the default is to convert everything.
3358
     *                              </p>
3359
     *
3360
     * @psalm-pure
3361
     *
3362
     * @return string the converted string.
3363
     *                </p>
3364
     *                <p>
3365
     *                If the input <i>string</i> contains an invalid code unit
3366
     *                sequence within the given <i>encoding</i> an empty string
3367
     *                will be returned, unless either the <b>ENT_IGNORE</b> or
3368
     *                <b>ENT_SUBSTITUTE</b> flags are set
3369
     */
3370 8
    public static function htmlspecialchars(
3371
        string $str,
3372
        int $flags = \ENT_COMPAT,
3373
        string $encoding = 'UTF-8',
3374
        bool $double_encode = true
3375
    ): string {
3376 8
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
3377 8
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
3378
        }
3379
3380 8
        return \htmlspecialchars(
3381 8
            $str,
3382 8
            $flags,
3383 8
            $encoding,
3384 8
            $double_encode
3385
        );
3386
    }
3387
3388
    /**
3389
     * Checks whether iconv is available on the server.
3390
     *
3391
     * @psalm-pure
3392
     *
3393
     * @return bool
3394
     *              <p><strong>true</strong> if available, <strong>false</strong> otherwise</p>
3395
     *
3396
     * @internal <p>Please do not use it anymore, we will make is private in next major version.</p>
3397
     */
3398
    public static function iconv_loaded(): bool
3399
    {
3400
        return \extension_loaded('iconv');
3401
    }
3402
3403
    /**
3404
     * alias for "UTF8::decimal_to_chr()"
3405
     *
3406
     * @param int|string $int
3407
     *
3408
     * @phpstan-param int|numeric-string $int
3409
     *
3410
     * @psalm-pure
3411
     *
3412
     * @return string
3413
     *
3414
     * @see        UTF8::decimal_to_chr()
3415
     * @deprecated <p>please use "UTF8::decimal_to_chr()"</p>
3416
     */
3417 4
    public static function int_to_chr($int): string
3418
    {
3419 4
        return self::decimal_to_chr($int);
3420
    }
3421
3422
    /**
3423
     * Converts Integer to hexadecimal U+xxxx code point representation.
3424
     *
3425
     * INFO: opposite to UTF8::hex_to_int()
3426
     *
3427
     * EXAMPLE: <code>UTF8::int_to_hex(241); // 'U+00f1'</code>
3428
     *
3429
     * @param int    $int    <p>The integer to be converted to hexadecimal code point.</p>
3430
     * @param string $prefix [optional]
3431
     *
3432
     * @psalm-pure
3433
     *
3434
     * @return string the code point, or empty string on failure
3435
     */
3436 6
    public static function int_to_hex(int $int, string $prefix = 'U+'): string
3437
    {
3438 6
        $hex = \dechex($int);
3439
3440 6
        $hex = (\strlen($hex) < 4 ? \substr('0000' . $hex, -4) : $hex);
3441
3442 6
        return $prefix . $hex . '';
3443
    }
3444
3445
    /**
3446
     * Checks whether intl-char is available on the server.
3447
     *
3448
     * @psalm-pure
3449
     *
3450
     * @return bool
3451
     *              <p><strong>true</strong> if available, <strong>false</strong> otherwise</p>
3452
     *
3453
     * @internal <p>Please do not use it anymore, we will make is private in next major version.</p>
3454
     */
3455
    public static function intlChar_loaded(): bool
3456
    {
3457
        return \class_exists('IntlChar');
3458
    }
3459
3460
    /**
3461
     * Checks whether intl is available on the server.
3462
     *
3463
     * @psalm-pure
3464
     *
3465
     * @return bool
3466
     *              <p><strong>true</strong> if available, <strong>false</strong> otherwise</p>
3467
     *
3468
     * @internal <p>Please do not use it anymore, we will make is private in next major version.</p>
3469
     */
3470 5
    public static function intl_loaded(): bool
3471
    {
3472 5
        return \extension_loaded('intl');
3473
    }
3474
3475
    /**
3476
     * alias for "UTF8::is_ascii()"
3477
     *
3478
     * @param string $str
3479
     *
3480
     * @psalm-pure
3481
     *
3482
     * @return bool
3483
     *
3484
     * @see        UTF8::is_ascii()
3485
     * @deprecated <p>please use "UTF8::is_ascii()"</p>
3486
     */
3487 2
    public static function isAscii(string $str): bool
3488
    {
3489 2
        return ASCII::is_ascii($str);
3490
    }
3491
3492
    /**
3493
     * alias for "UTF8::is_base64()"
3494
     *
3495
     * @param string $str
3496
     *
3497
     * @psalm-pure
3498
     *
3499
     * @return bool
3500
     *
3501
     * @see        UTF8::is_base64()
3502
     * @deprecated <p>please use "UTF8::is_base64()"</p>
3503
     */
3504 2
    public static function isBase64($str): bool
3505
    {
3506 2
        return self::is_base64($str);
3507
    }
3508
3509
    /**
3510
     * alias for "UTF8::is_binary()"
3511
     *
3512
     * @param int|string $str
3513
     * @param bool       $strict
3514
     *
3515
     * @psalm-pure
3516
     *
3517
     * @return bool
3518
     *
3519
     * @see        UTF8::is_binary()
3520
     * @deprecated <p>please use "UTF8::is_binary()"</p>
3521
     */
3522 4
    public static function isBinary($str, bool $strict = false): bool
3523
    {
3524 4
        return self::is_binary($str, $strict);
3525
    }
3526
3527
    /**
3528
     * alias for "UTF8::is_bom()"
3529
     *
3530
     * @param string $utf8_chr
3531
     *
3532
     * @psalm-pure
3533
     *
3534
     * @return bool
3535
     *
3536
     * @see        UTF8::is_bom()
3537
     * @deprecated <p>please use "UTF8::is_bom()"</p>
3538
     */
3539 2
    public static function isBom(string $utf8_chr): bool
3540
    {
3541 2
        return self::is_bom($utf8_chr);
3542
    }
3543
3544
    /**
3545
     * alias for "UTF8::is_html()"
3546
     *
3547
     * @param string $str
3548
     *
3549
     * @psalm-pure
3550
     *
3551
     * @return bool
3552
     *
3553
     * @see        UTF8::is_html()
3554
     * @deprecated <p>please use "UTF8::is_html()"</p>
3555
     */
3556 2
    public static function isHtml(string $str): bool
3557
    {
3558 2
        return self::is_html($str);
3559
    }
3560
3561
    /**
3562
     * alias for "UTF8::is_json()"
3563
     *
3564
     * @param string $str
3565
     *
3566
     * @return bool
3567
     *
3568
     * @see        UTF8::is_json()
3569
     * @deprecated <p>please use "UTF8::is_json()"</p>
3570
     */
3571 1
    public static function isJson(string $str): bool
3572
    {
3573 1
        return self::is_json($str);
3574
    }
3575
3576
    /**
3577
     * alias for "UTF8::is_utf16()"
3578
     *
3579
     * @param string $str
3580
     *
3581
     * @psalm-pure
3582
     *
3583
     * @return false|int
3584
     *                   <strong>false</strong> if is't not UTF16,<br>
3585
     *                   <strong>1</strong> for UTF-16LE,<br>
3586
     *                   <strong>2</strong> for UTF-16BE
3587
     *
3588
     * @see        UTF8::is_utf16()
3589
     * @deprecated <p>please use "UTF8::is_utf16()"</p>
3590
     */
3591 2
    public static function isUtf16($str)
3592
    {
3593 2
        return self::is_utf16($str);
3594
    }
3595
3596
    /**
3597
     * alias for "UTF8::is_utf32()"
3598
     *
3599
     * @param string $str
3600
     *
3601
     * @psalm-pure
3602
     *
3603
     * @return false|int
3604
     *                   <strong>false</strong> if is't not UTF16,
3605
     *                   <strong>1</strong> for UTF-32LE,
3606
     *                   <strong>2</strong> for UTF-32BE
3607
     *
3608
     * @see        UTF8::is_utf32()
3609
     * @deprecated <p>please use "UTF8::is_utf32()"</p>
3610
     */
3611 2
    public static function isUtf32($str)
3612
    {
3613 2
        return self::is_utf32($str);
3614
    }
3615
3616
    /**
3617
     * alias for "UTF8::is_utf8()"
3618
     *
3619
     * @param string $str
3620
     * @param bool   $strict
3621
     *
3622
     * @psalm-pure
3623
     *
3624
     * @return bool
3625
     *
3626
     * @see        UTF8::is_utf8()
3627
     * @deprecated <p>please use "UTF8::is_utf8()"</p>
3628
     */
3629 17
    public static function isUtf8($str, bool $strict = false): bool
3630
    {
3631 17
        return self::is_utf8($str, $strict);
3632
    }
3633
3634
    /**
3635
     * Returns true if the string contains only alphabetic chars, false otherwise.
3636
     *
3637
     * @param string $str <p>The input string.</p>
3638
     *
3639
     * @psalm-pure
3640
     *
3641
     * @return bool
3642
     *              <p>Whether or not $str contains only alphabetic chars.</p>
3643
     */
3644 10
    public static function is_alpha(string $str): bool
3645
    {
3646 10
        if (self::$SUPPORT['mbstring'] === true) {
3647
            /** @noinspection PhpComposerExtensionStubsInspection */
3648 10
            return \mb_ereg_match('^[[:alpha:]]*$', $str);
3649
        }
3650
3651
        return self::str_matches_pattern($str, '^[[:alpha:]]*$');
3652
    }
3653
3654
    /**
3655
     * Returns true if the string contains only alphabetic and numeric chars, false otherwise.
3656
     *
3657
     * @param string $str <p>The input string.</p>
3658
     *
3659
     * @psalm-pure
3660
     *
3661
     * @return bool
3662
     *              <p>Whether or not $str contains only alphanumeric chars.</p>
3663
     */
3664 13
    public static function is_alphanumeric(string $str): bool
3665
    {
3666 13
        if (self::$SUPPORT['mbstring'] === true) {
3667
            /** @noinspection PhpComposerExtensionStubsInspection */
3668 13
            return \mb_ereg_match('^[[:alnum:]]*$', $str);
3669
        }
3670
3671
        return self::str_matches_pattern($str, '^[[:alnum:]]*$');
3672
    }
3673
3674
    /**
3675
     * Returns true if the string contains only punctuation chars, false otherwise.
3676
     *
3677
     * @param string $str <p>The input string.</p>
3678
     *
3679
     * @psalm-pure
3680
     *
3681
     * @return bool
3682
     *              <p>Whether or not $str contains only punctuation chars.</p>
3683
     */
3684 10
    public static function is_punctuation(string $str): bool
3685
    {
3686 10
        return self::str_matches_pattern($str, '^[[:punct:]]*$');
3687
    }
3688
3689
    /**
3690
     * Returns true if the string contains only printable (non-invisible) chars, false otherwise.
3691
     *
3692
     * @param string $str <p>The input string.</p>
3693
     *
3694
     * @psalm-pure
3695
     *
3696
     * @return bool
3697
     *              <p>Whether or not $str contains only printable (non-invisible) chars.</p>
3698
     */
3699 1
    public static function is_printable(string $str): bool
3700
    {
3701 1
        return self::remove_invisible_characters($str) === $str;
3702
    }
3703
3704
    /**
3705
     * Checks if a string is 7 bit ASCII.
3706
     *
3707
     * EXAMPLE: <code>UTF8::is_ascii('白'); // false</code>
3708
     *
3709
     * @param string $str <p>The string to check.</p>
3710
     *
3711
     * @psalm-pure
3712
     *
3713
     * @return bool
3714
     *              <p>
3715
     *              <strong>true</strong> if it is ASCII<br>
3716
     *              <strong>false</strong> otherwise
3717
     *              </p>
3718
     */
3719 8
    public static function is_ascii(string $str): bool
3720
    {
3721 8
        return ASCII::is_ascii($str);
3722
    }
3723
3724
    /**
3725
     * Returns true if the string is base64 encoded, false otherwise.
3726
     *
3727
     * EXAMPLE: <code>UTF8::is_base64('4KSu4KWL4KSo4KS/4KSa'); // true</code>
3728
     *
3729
     * @param string|null $str                   <p>The input string.</p>
3730
     * @param bool        $empty_string_is_valid [optional] <p>Is an empty string valid base64 or not?</p>
3731
     *
3732
     * @psalm-pure
3733
     *
3734
     * @return bool
3735
     *              <p>Whether or not $str is base64 encoded.</p>
3736
     */
3737 16
    public static function is_base64($str, bool $empty_string_is_valid = false): bool
3738
    {
3739
        if (
3740 16
            !$empty_string_is_valid
3741
            &&
3742 16
            $str === ''
3743
        ) {
3744 3
            return false;
3745
        }
3746
3747 15
        if (!\is_string($str)) {
3748 2
            return false;
3749
        }
3750
3751 15
        $base64String = \base64_decode($str, true);
3752
3753 15
        return $base64String !== false && \base64_encode($base64String) === $str;
3754
    }
3755
3756
    /**
3757
     * Check if the input is binary... (is look like a hack).
3758
     *
3759
     * EXAMPLE: <code>UTF8::is_binary(01); // true</code>
3760
     *
3761
     * @param int|string $input
3762
     * @param bool       $strict
3763
     *
3764
     * @psalm-pure
3765
     *
3766
     * @return bool
3767
     */
3768 40
    public static function is_binary($input, bool $strict = false): bool
3769
    {
3770 40
        $input = (string) $input;
3771 40
        if ($input === '') {
3772 10
            return false;
3773
        }
3774
3775 40
        if (\preg_match('~^[01]+$~', $input)) {
3776 13
            return true;
3777
        }
3778
3779 40
        $ext = self::get_file_type($input);
3780 40
        if ($ext['type'] === 'binary') {
3781 7
            return true;
3782
        }
3783
3784 39
        $test_length = \strlen($input);
3785 39
        $test_null_counting = \substr_count($input, "\x0", 0, $test_length);
3786 39
        if (($test_null_counting / $test_length) > 0.25) {
3787 15
            return true;
3788
        }
3789
3790 35
        if ($strict) {
3791 35
            if (self::$SUPPORT['finfo'] === false) {
3792
                throw new \RuntimeException('ext-fileinfo: is not installed');
3793
            }
3794
3795
            /**
3796
             * @noinspection   PhpComposerExtensionStubsInspection
3797
             * @psalm-suppress ImpureMethodCall - it will return the same result for the same file ...
3798
             */
3799 35
            $finfo_encoding = (new \finfo(\FILEINFO_MIME_ENCODING))->buffer($input);
3800 35
            if ($finfo_encoding && $finfo_encoding === 'binary') {
3801 15
                return true;
3802
            }
3803
        }
3804
3805 31
        return false;
3806
    }
3807
3808
    /**
3809
     * Check if the file is binary.
3810
     *
3811
     * EXAMPLE: <code>UTF8::is_binary('./utf32.txt'); // true</code>
3812
     *
3813
     * @param string $file
3814
     *
3815
     * @return bool
3816
     */
3817 6
    public static function is_binary_file($file): bool
3818
    {
3819
        // init
3820 6
        $block = '';
3821
3822 6
        $fp = \fopen($file, 'rb');
3823 6
        if (\is_resource($fp)) {
3824 6
            $block = \fread($fp, 512);
3825 6
            \fclose($fp);
3826
        }
3827
3828 6
        if ($block === '' || $block === false) {
3829 2
            return false;
3830
        }
3831
3832 6
        return self::is_binary($block, true);
3833
    }
3834
3835
    /**
3836
     * Returns true if the string contains only whitespace chars, false otherwise.
3837
     *
3838
     * @param string $str <p>The input string.</p>
3839
     *
3840
     * @psalm-pure
3841
     *
3842
     * @return bool
3843
     *              <p>Whether or not $str contains only whitespace characters.</p>
3844
     */
3845 15
    public static function is_blank(string $str): bool
3846
    {
3847 15
        if (self::$SUPPORT['mbstring'] === true) {
3848
            /** @noinspection PhpComposerExtensionStubsInspection */
3849 15
            return \mb_ereg_match('^[[:space:]]*$', $str);
3850
        }
3851
3852
        return self::str_matches_pattern($str, '^[[:space:]]*$');
3853
    }
3854
3855
    /**
3856
     * Checks if the given string is equal to any "Byte Order Mark".
3857
     *
3858
     * WARNING: Use "UTF8::string_has_bom()" if you will check BOM in a string.
3859
     *
3860
     * EXAMPLE: <code>UTF8::is_bom("\xef\xbb\xbf"); // true</code>
3861
     *
3862
     * @param string $str <p>The input string.</p>
3863
     *
3864
     * @psalm-pure
3865
     *
3866
     * @return bool
3867
     *              <p><strong>true</strong> if the $utf8_chr is Byte Order Mark, <strong>false</strong> otherwise.</p>
3868
     */
3869 2
    public static function is_bom($str): bool
3870
    {
3871
        /** @noinspection PhpUnusedLocalVariableInspection */
3872 2
        foreach (self::$BOM as $bom_string => &$bom_byte_length) {
3873 2
            if ($str === $bom_string) {
3874 2
                return true;
3875
            }
3876
        }
3877
3878 2
        return false;
3879
    }
3880
3881
    /**
3882
     * Determine whether the string is considered to be empty.
3883
     *
3884
     * A variable is considered empty if it does not exist or if its value equals FALSE.
3885
     * empty() does not generate a warning if the variable does not exist.
3886
     *
3887
     * @param array|float|int|string $str
3888
     *
3889
     * @psalm-pure
3890
     *
3891
     * @return bool
3892
     *              <p>Whether or not $str is empty().</p>
3893
     */
3894 1
    public static function is_empty($str): bool
3895
    {
3896 1
        return empty($str);
3897
    }
3898
3899
    /**
3900
     * Returns true if the string contains only hexadecimal chars, false otherwise.
3901
     *
3902
     * @param string $str <p>The input string.</p>
3903
     *
3904
     * @psalm-pure
3905
     *
3906
     * @return bool
3907
     *              <p>Whether or not $str contains only hexadecimal chars.</p>
3908
     */
3909 13
    public static function is_hexadecimal(string $str): bool
3910
    {
3911 13
        if (self::$SUPPORT['mbstring'] === true) {
3912
            /** @noinspection PhpComposerExtensionStubsInspection */
3913 13
            return \mb_ereg_match('^[[:xdigit:]]*$', $str);
3914
        }
3915
3916
        return self::str_matches_pattern($str, '^[[:xdigit:]]*$');
3917
    }
3918
3919
    /**
3920
     * Check if the string contains any HTML tags.
3921
     *
3922
     * EXAMPLE: <code>UTF8::is_html('<b>lall</b>'); // true</code>
3923
     *
3924
     * @param string $str <p>The input string.</p>
3925
     *
3926
     * @psalm-pure
3927
     *
3928
     * @return bool
3929
     *              <p>Whether or not $str contains html elements.</p>
3930
     */
3931 3
    public static function is_html(string $str): bool
3932
    {
3933 3
        if ($str === '') {
3934 3
            return false;
3935
        }
3936
3937
        // init
3938 3
        $matches = [];
3939
3940 3
        $str = self::emoji_encode($str); // hack for emoji support :/
3941
3942 3
        \preg_match("/<\\/?\\w+(?:(?:\\s+\\w+(?:\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)*\\s*|\\s*)\\/?>/u", $str, $matches);
3943
3944 3
        return $matches !== [];
3945
    }
3946
3947
    /**
3948
     * Check if $url is an correct url.
3949
     *
3950
     * @param string $url
3951
     * @param bool   $disallow_localhost
3952
     *
3953
     * @psalm-pure
3954
     *
3955
     * @return bool
3956
     */
3957 1
    public static function is_url(string $url, bool $disallow_localhost = false): bool
3958
    {
3959 1
        if ($url === '') {
3960 1
            return false;
3961
        }
3962
3963
        // WARNING: keep this as hack protection
3964 1
        if (!self::str_istarts_with_any($url, ['http://', 'https://'])) {
3965 1
            return false;
3966
        }
3967
3968
        // e.g. -> the server itself connect to "https://foo.localhost/phpmyadmin/...
3969 1
        if ($disallow_localhost) {
3970 1
            if (self::str_istarts_with_any(
3971 1
                $url,
3972
                [
3973 1
                    'http://localhost',
3974
                    'https://localhost',
3975
                    'http://127.0.0.1',
3976
                    'https://127.0.0.1',
3977
                    'http://::1',
3978
                    'https://::1',
3979
                ]
3980
            )) {
3981 1
                return false;
3982
            }
3983
3984 1
            $regex = '/^(?:http(?:s)?:\/\/).*?(?:\.localhost)/iu';
3985
            /** @noinspection BypassedUrlValidationInspection */
3986 1
            if (\preg_match($regex, $url)) {
3987 1
                return false;
3988
            }
3989
        }
3990
3991
        // INFO: this is needed for e.g. "http://müller.de/" (internationalized domain names) and non ASCII-parameters
3992
        /** @noinspection SuspiciousAssignmentsInspection - false-positive - https://github.com/kalessil/phpinspectionsea/issues/1500 */
3993 1
        $regex = '/^(?:http(?:s)?:\\/\\/)(?:[\p{L}0-9][\p{L}0-9_-]*(?:\\.[\p{L}0-9][\p{L}0-9_-]*))(?:\\d+)?(?:\\/\\.*)?/iu';
3994
        /** @noinspection BypassedUrlValidationInspection */
3995 1
        if (\preg_match($regex, $url)) {
3996 1
            return true;
3997
        }
3998
3999
        /** @noinspection BypassedUrlValidationInspection */
4000 1
        return \filter_var($url, \FILTER_VALIDATE_URL) !== false;
4001
    }
4002
4003
    /**
4004
     * Try to check if "$str" is a JSON-string.
4005
     *
4006
     * EXAMPLE: <code>UTF8::is_json('{"array":[1,"¥","ä"]}'); // true</code>
4007
     *
4008
     * @param string $str                                    <p>The input string.</p>
4009
     * @param bool   $only_array_or_object_results_are_valid [optional] <p>Only array and objects are valid json
4010
     *                                                       results.</p>
4011
     *
4012
     * @return bool
4013
     *              <p>Whether or not the $str is in JSON format.</p>
4014
     */
4015 42
    public static function is_json(string $str, bool $only_array_or_object_results_are_valid = true): bool
4016
    {
4017 42
        if ($str === '') {
4018 4
            return false;
4019
        }
4020
4021 40
        if (self::$SUPPORT['json'] === false) {
4022
            throw new \RuntimeException('ext-json: is not installed');
4023
        }
4024
4025 40
        $jsonOrNull = self::json_decode($str);
4026 40
        if ($jsonOrNull === null && \strtoupper($str) !== 'NULL') {
4027 18
            return false;
4028
        }
4029
4030
        if (
4031 24
            $only_array_or_object_results_are_valid
4032
            &&
4033 24
            !\is_object($jsonOrNull)
4034
            &&
4035 24
            !\is_array($jsonOrNull)
4036
        ) {
4037 5
            return false;
4038
        }
4039
4040
        /** @noinspection PhpComposerExtensionStubsInspection */
4041 19
        return \json_last_error() === \JSON_ERROR_NONE;
4042
    }
4043
4044
    /**
4045
     * @param string $str <p>The input string.</p>
4046
     *
4047
     * @psalm-pure
4048
     *
4049
     * @return bool
4050
     *              <p>Whether or not $str contains only lowercase chars.</p>
4051
     */
4052 8
    public static function is_lowercase(string $str): bool
4053
    {
4054 8
        if (self::$SUPPORT['mbstring'] === true) {
4055
            /** @noinspection PhpComposerExtensionStubsInspection */
4056 8
            return \mb_ereg_match('^[[:lower:]]*$', $str);
4057
        }
4058
4059
        return self::str_matches_pattern($str, '^[[:lower:]]*$');
4060
    }
4061
4062
    /**
4063
     * Returns true if the string is serialized, false otherwise.
4064
     *
4065
     * @param string $str <p>The input string.</p>
4066
     *
4067
     * @psalm-pure
4068
     *
4069
     * @return bool
4070
     *              <p>Whether or not $str is serialized.</p>
4071
     */
4072 7
    public static function is_serialized(string $str): bool
4073
    {
4074 7
        if ($str === '') {
4075 1
            return false;
4076
        }
4077
4078
        /** @noinspection PhpUsageOfSilenceOperatorInspection */
4079
        /** @noinspection UnserializeExploitsInspection */
4080 6
        return $str === 'b:0;'
4081
               ||
4082 6
               @\unserialize($str) !== false;
4083
    }
4084
4085
    /**
4086
     * Returns true if the string contains only lower case chars, false
4087
     * otherwise.
4088
     *
4089
     * @param string $str <p>The input string.</p>
4090
     *
4091
     * @psalm-pure
4092
     *
4093
     * @return bool
4094
     *              <p>Whether or not $str contains only lower case characters.</p>
4095
     */
4096 8
    public static function is_uppercase(string $str): bool
4097
    {
4098 8
        if (self::$SUPPORT['mbstring'] === true) {
4099
            /** @noinspection PhpComposerExtensionStubsInspection */
4100 8
            return \mb_ereg_match('^[[:upper:]]*$', $str);
4101
        }
4102
4103
        return self::str_matches_pattern($str, '^[[:upper:]]*$');
4104
    }
4105
4106
    /**
4107
     * Check if the string is UTF-16.
4108
     *
4109
     * EXAMPLE: <code>
4110
     * UTF8::is_utf16(file_get_contents('utf-16-le.txt')); // 1
4111
     * //
4112
     * UTF8::is_utf16(file_get_contents('utf-16-be.txt')); // 2
4113
     * //
4114
     * UTF8::is_utf16(file_get_contents('utf-8.txt')); // false
4115
     * </code>
4116
     *
4117
     * @param string $str                       <p>The input string.</p>
4118
     * @param bool   $check_if_string_is_binary
4119
     *
4120
     * @psalm-pure
4121
     *
4122
     * @return false|int
4123
     *                   <strong>false</strong> if is't not UTF-16,<br>
4124
     *                   <strong>1</strong> for UTF-16LE,<br>
4125
     *                   <strong>2</strong> for UTF-16BE
4126
     */
4127 22
    public static function is_utf16($str, bool $check_if_string_is_binary = true)
4128
    {
4129
        // init
4130 22
        $str = (string) $str;
4131 22
        $str_chars = [];
4132
4133
        if (
4134 22
            $check_if_string_is_binary
4135
            &&
4136 22
            !self::is_binary($str, true)
4137
        ) {
4138 2
            return false;
4139
        }
4140
4141 22
        if (self::$SUPPORT['mbstring'] === false) {
4142
            /**
4143
             * @psalm-suppress ImpureFunctionCall - is is only a warning
4144
             */
4145 3
            \trigger_error('UTF8::is_utf16() without mbstring may did not work correctly', \E_USER_WARNING);
4146
        }
4147
4148 22
        $str = self::remove_bom($str);
4149
4150 22
        $maybe_utf16le = 0;
4151 22
        $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-16LE');
4152 22
        if ($test) {
4153 15
            $test2 = \mb_convert_encoding($test, 'UTF-16LE', 'UTF-8');
4154 15
            $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-16LE');
4155 15
            if ($test3 === $test) {
4156
                /**
4157
                 * @psalm-suppress RedundantCondition
4158
                 */
4159 15
                if ($str_chars === []) {
4160 15
                    $str_chars = self::count_chars($str, true, false);
4161
                }
4162 15
                foreach (self::count_chars($test3) as $test3char => &$test3charEmpty) {
0 ignored issues
show
Bug introduced by
The expression self::count_chars($test3) cannot be used as a reference.

Let?s assume that you have the following foreach statement:

foreach ($array as &$itemValue) { }

$itemValue is assigned by reference. This is possible because the expression (in the example $array) can be used as a reference target.

However, if we were to replace $array with something different like the result of a function call as in

foreach (getArray() as &$itemValue) { }

then assigning by reference is not possible anymore as there is no target that could be modified.

Available Fixes

1. Do not assign by reference
foreach (getArray() as $itemValue) { }
2. Assign to a local variable first
$array = getArray();
foreach ($array as &$itemValue) {}
3. Return a reference
function &getArray() { $array = array(); return $array; }

foreach (getArray() as &$itemValue) { }
Loading history...
4163 15
                    if (\in_array($test3char, $str_chars, true)) {
4164 15
                        ++$maybe_utf16le;
4165
                    }
4166
                }
4167 15
                unset($test3charEmpty);
4168
            }
4169
        }
4170
4171 22
        $maybe_utf16be = 0;
4172 22
        $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-16BE');
4173 22
        if ($test) {
4174 15
            $test2 = \mb_convert_encoding($test, 'UTF-16BE', 'UTF-8');
4175 15
            $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-16BE');
4176 15
            if ($test3 === $test) {
4177 15
                if ($str_chars === []) {
4178 7
                    $str_chars = self::count_chars($str, true, false);
4179
                }
4180 15
                foreach (self::count_chars($test3) as $test3char => &$test3charEmpty) {
0 ignored issues
show
Bug introduced by
The expression self::count_chars($test3) cannot be used as a reference.

Let?s assume that you have the following foreach statement:

foreach ($array as &$itemValue) { }

$itemValue is assigned by reference. This is possible because the expression (in the example $array) can be used as a reference target.

However, if we were to replace $array with something different like the result of a function call as in

foreach (getArray() as &$itemValue) { }

then assigning by reference is not possible anymore as there is no target that could be modified.

Available Fixes

1. Do not assign by reference
foreach (getArray() as $itemValue) { }
2. Assign to a local variable first
$array = getArray();
foreach ($array as &$itemValue) {}
3. Return a reference
function &getArray() { $array = array(); return $array; }

foreach (getArray() as &$itemValue) { }
Loading history...
4181 15
                    if (\in_array($test3char, $str_chars, true)) {
4182 15
                        ++$maybe_utf16be;
4183
                    }
4184
                }
4185 15
                unset($test3charEmpty);
4186
            }
4187
        }
4188
4189 22
        if ($maybe_utf16be !== $maybe_utf16le) {
4190 7
            if ($maybe_utf16le > $maybe_utf16be) {
4191 5
                return 1;
4192
            }
4193
4194 6
            return 2;
4195
        }
4196
4197 18
        return false;
4198
    }
4199
4200
    /**
4201
     * Check if the string is UTF-32.
4202
     *
4203
     * EXAMPLE: <code>
4204
     * UTF8::is_utf32(file_get_contents('utf-32-le.txt')); // 1
4205
     * //
4206
     * UTF8::is_utf32(file_get_contents('utf-32-be.txt')); // 2
4207
     * //
4208
     * UTF8::is_utf32(file_get_contents('utf-8.txt')); // false
4209
     * </code>
4210
     *
4211
     * @param string $str                       <p>The input string.</p>
4212
     * @param bool   $check_if_string_is_binary
4213
     *
4214
     * @psalm-pure
4215
     *
4216
     * @return false|int
4217
     *                   <strong>false</strong> if is't not UTF-32,<br>
4218
     *                   <strong>1</strong> for UTF-32LE,<br>
4219
     *                   <strong>2</strong> for UTF-32BE
4220
     */
4221 20
    public static function is_utf32($str, bool $check_if_string_is_binary = true)
4222
    {
4223
        // init
4224 20
        $str = (string) $str;
4225 20
        $str_chars = [];
4226
4227
        if (
4228 20
            $check_if_string_is_binary
4229
            &&
4230 20
            !self::is_binary($str, true)
4231
        ) {
4232 2
            return false;
4233
        }
4234
4235 20
        if (self::$SUPPORT['mbstring'] === false) {
4236
            /**
4237
             * @psalm-suppress ImpureFunctionCall - is is only a warning
4238
             */
4239 3
            \trigger_error('UTF8::is_utf32() without mbstring may did not work correctly', \E_USER_WARNING);
4240
        }
4241
4242 20
        $str = self::remove_bom($str);
4243
4244 20
        $maybe_utf32le = 0;
4245 20
        $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-32LE');
4246 20
        if ($test) {
4247 13
            $test2 = \mb_convert_encoding($test, 'UTF-32LE', 'UTF-8');
4248 13
            $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-32LE');
4249 13
            if ($test3 === $test) {
4250
                /**
4251
                 * @psalm-suppress RedundantCondition
4252
                 */
4253 13
                if ($str_chars === []) {
4254 13
                    $str_chars = self::count_chars($str, true, false);
4255
                }
4256 13
                foreach (self::count_chars($test3) as $test3char => &$test3charEmpty) {
0 ignored issues
show
Bug introduced by
The expression self::count_chars($test3) cannot be used as a reference.

Let?s assume that you have the following foreach statement:

foreach ($array as &$itemValue) { }

$itemValue is assigned by reference. This is possible because the expression (in the example $array) can be used as a reference target.

However, if we were to replace $array with something different like the result of a function call as in

foreach (getArray() as &$itemValue) { }

then assigning by reference is not possible anymore as there is no target that could be modified.

Available Fixes

1. Do not assign by reference
foreach (getArray() as $itemValue) { }
2. Assign to a local variable first
$array = getArray();
foreach ($array as &$itemValue) {}
3. Return a reference
function &getArray() { $array = array(); return $array; }

foreach (getArray() as &$itemValue) { }
Loading history...
4257 13
                    if (\in_array($test3char, $str_chars, true)) {
4258 13
                        ++$maybe_utf32le;
4259
                    }
4260
                }
4261 13
                unset($test3charEmpty);
4262
            }
4263
        }
4264
4265 20
        $maybe_utf32be = 0;
4266 20
        $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-32BE');
4267 20
        if ($test) {
4268 13
            $test2 = \mb_convert_encoding($test, 'UTF-32BE', 'UTF-8');
4269 13
            $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-32BE');
4270 13
            if ($test3 === $test) {
4271 13
                if ($str_chars === []) {
4272 7
                    $str_chars = self::count_chars($str, true, false);
4273
                }
4274 13
                foreach (self::count_chars($test3) as $test3char => &$test3charEmpty) {
0 ignored issues
show
Bug introduced by
The expression self::count_chars($test3) cannot be used as a reference.

Let?s assume that you have the following foreach statement:

foreach ($array as &$itemValue) { }

$itemValue is assigned by reference. This is possible because the expression (in the example $array) can be used as a reference target.

However, if we were to replace $array with something different like the result of a function call as in

foreach (getArray() as &$itemValue) { }

then assigning by reference is not possible anymore as there is no target that could be modified.

Available Fixes

1. Do not assign by reference
foreach (getArray() as $itemValue) { }
2. Assign to a local variable first
$array = getArray();
foreach ($array as &$itemValue) {}
3. Return a reference
function &getArray() { $array = array(); return $array; }

foreach (getArray() as &$itemValue) { }
Loading history...
4275 13
                    if (\in_array($test3char, $str_chars, true)) {
4276 13
                        ++$maybe_utf32be;
4277
                    }
4278
                }
4279 13
                unset($test3charEmpty);
4280
            }
4281
        }
4282
4283 20
        if ($maybe_utf32be !== $maybe_utf32le) {
4284 3
            if ($maybe_utf32le > $maybe_utf32be) {
4285 2
                return 1;
4286
            }
4287
4288 3
            return 2;
4289
        }
4290
4291 20
        return false;
4292
    }
4293
4294
    /**
4295
     * Checks whether the passed input contains only byte sequences that appear valid UTF-8.
4296
     *
4297
     * EXAMPLE: <code>
4298
     * UTF8::is_utf8(['Iñtërnâtiônàlizætiøn', 'foo']); // true
4299
     * //
4300
     * UTF8::is_utf8(["Iñtërnâtiônàlizætiøn\xA0\xA1", 'bar']); // false
4301
     * </code>
4302
     *
4303
     * @param int|string|string[]|null $str    <p>The input to be checked.</p>
4304
     * @param bool                     $strict <p>Check also if the string is not UTF-16 or UTF-32.</p>
4305
     *
4306
     * @psalm-pure
4307
     *
4308
     * @return bool
4309
     */
4310 83
    public static function is_utf8($str, bool $strict = false): bool
4311
    {
4312 83
        if (\is_array($str)) {
4313 2
            foreach ($str as &$v) {
4314 2
                if (!self::is_utf8($v, $strict)) {
4315 2
                    return false;
4316
                }
4317
            }
4318
4319
            return true;
4320
        }
4321
4322 83
        return self::is_utf8_string((string) $str, $strict);
4323
    }
4324
4325
    /**
4326
     * (PHP 5 &gt;= 5.2.0, PECL json &gt;= 1.2.0)<br/>
4327
     * Decodes a JSON string
4328
     *
4329
     * EXAMPLE: <code>UTF8::json_decode('[1,"\u00a5","\u00e4"]'); // array(1, '¥', 'ä')</code>
4330
     *
4331
     * @see http://php.net/manual/en/function.json-decode.php
4332
     *
4333
     * @param string $json    <p>
4334
     *                        The <i>json</i> string being decoded.
4335
     *                        </p>
4336
     *                        <p>
4337
     *                        This function only works with UTF-8 encoded strings.
4338
     *                        </p>
4339
     *                        <p>PHP implements a superset of
4340
     *                        JSON - it will also encode and decode scalar types and <b>NULL</b>. The JSON standard
4341
     *                        only supports these values when they are nested inside an array or an object.
4342
     *                        </p>
4343
     * @param bool   $assoc   [optional] <p>
4344
     *                        When <b>TRUE</b>, returned objects will be converted into
4345
     *                        associative arrays.
4346
     *                        </p>
4347
     * @param int    $depth   [optional] <p>
4348
     *                        User specified recursion depth.
4349
     *                        </p>
4350
     * @param int    $options [optional] <p>
4351
     *                        Bitmask of JSON decode options. Currently only
4352
     *                        <b>JSON_BIGINT_AS_STRING</b>
4353
     *                        is supported (default is to cast large integers as floats)
4354
     *                        </p>
4355
     *
4356
     * @psalm-pure
4357
     *
4358
     * @return mixed
4359
     *               <p>The value encoded in <i>json</i> in appropriate PHP type. Values true, false and
4360
     *               null (case-insensitive) are returned as <b>TRUE</b>, <b>FALSE</b> and <b>NULL</b> respectively.
4361
     *               <b>NULL</b> is returned if the <i>json</i> cannot be decoded or if the encoded data
4362
     *               is deeper than the recursion limit.</p>
4363
     */
4364 43
    public static function json_decode(
4365
        string $json,
4366
        bool $assoc = false,
4367
        int $depth = 512,
4368
        int $options = 0
4369
    ) {
4370 43
        $json = self::filter($json);
4371
4372 43
        if (self::$SUPPORT['json'] === false) {
4373
            throw new \RuntimeException('ext-json: is not installed');
4374
        }
4375
4376
        /** @noinspection PhpComposerExtensionStubsInspection */
4377 43
        return \json_decode($json, $assoc, $depth, $options);
4378
    }
4379
4380
    /**
4381
     * (PHP 5 &gt;= 5.2.0, PECL json &gt;= 1.2.0)<br/>
4382
     * Returns the JSON representation of a value.
4383
     *
4384
     * EXAMPLE: <code>UTF8::json_enocde(array(1, '¥', 'ä')); // '[1,"\u00a5","\u00e4"]'</code>
4385
     *
4386
     * @see http://php.net/manual/en/function.json-encode.php
4387
     *
4388
     * @param mixed $value   <p>
4389
     *                       The <i>value</i> being encoded. Can be any type except
4390
     *                       a resource.
4391
     *                       </p>
4392
     *                       <p>
4393
     *                       All string data must be UTF-8 encoded.
4394
     *                       </p>
4395
     *                       <p>PHP implements a superset of
4396
     *                       JSON - it will also encode and decode scalar types and <b>NULL</b>. The JSON standard
4397
     *                       only supports these values when they are nested inside an array or an object.
4398
     *                       </p>
4399
     * @param int   $options [optional] <p>
4400
     *                       Bitmask consisting of <b>JSON_HEX_QUOT</b>,
4401
     *                       <b>JSON_HEX_TAG</b>,
4402
     *                       <b>JSON_HEX_AMP</b>,
4403
     *                       <b>JSON_HEX_APOS</b>,
4404
     *                       <b>JSON_NUMERIC_CHECK</b>,
4405
     *                       <b>JSON_PRETTY_PRINT</b>,
4406
     *                       <b>JSON_UNESCAPED_SLASHES</b>,
4407
     *                       <b>JSON_FORCE_OBJECT</b>,
4408
     *                       <b>JSON_UNESCAPED_UNICODE</b>. The behaviour of these
4409
     *                       constants is described on
4410
     *                       the JSON constants page.
4411
     *                       </p>
4412
     * @param int   $depth   [optional] <p>
4413
     *                       Set the maximum depth. Must be greater than zero.
4414
     *                       </p>
4415
     *
4416
     * @psalm-pure
4417
     *
4418
     * @return false|string
4419
     *                      A JSON encoded <strong>string</strong> on success or<br>
4420
     *                      <strong>FALSE</strong> on failure
4421
     */
4422 5
    public static function json_encode($value, int $options = 0, int $depth = 512)
4423
    {
4424 5
        $value = self::filter($value);
4425
4426 5
        if (self::$SUPPORT['json'] === false) {
4427
            throw new \RuntimeException('ext-json: is not installed');
4428
        }
4429
4430
        /** @noinspection PhpComposerExtensionStubsInspection */
4431 5
        return \json_encode($value, $options, $depth);
4432
    }
4433
4434
    /**
4435
     * Checks whether JSON is available on the server.
4436
     *
4437
     * @psalm-pure
4438
     *
4439
     * @return bool
4440
     *              <p><strong>true</strong> if available, <strong>false</strong> otherwise</p>
4441
     *
4442
     * @internal <p>Please do not use it anymore, we will make is private in next major version.</p>
4443
     */
4444
    public static function json_loaded(): bool
4445
    {
4446
        return \function_exists('json_decode');
4447
    }
4448
4449
    /**
4450
     * Makes string's first char lowercase.
4451
     *
4452
     * EXAMPLE: <code>UTF8::lcfirst('ÑTËRNÂTIÔNÀLIZÆTIØN'); // ñTËRNÂTIÔNÀLIZÆTIØN</code>
4453
     *
4454
     * @param string      $str                           <p>The input string</p>
4455
     * @param string      $encoding                      [optional] <p>Set the charset for e.g. "mb_" function</p>
4456
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
4457
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
4458
     *                                                   tr</p>
4459
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ
4460
     *                                                   -> ß</p>
4461
     *
4462
     * @psalm-pure
4463
     *
4464
     * @return string the resulting string
4465
     */
4466 46
    public static function lcfirst(
4467
        string $str,
4468
        string $encoding = 'UTF-8',
4469
        bool $clean_utf8 = false,
4470
        string $lang = null,
4471
        bool $try_to_keep_the_string_length = false
4472
    ): string {
4473 46
        if ($clean_utf8) {
4474
            $str = self::clean($str);
4475
        }
4476
4477 46
        $use_mb_functions = ($lang === null && !$try_to_keep_the_string_length);
4478
4479 46
        if ($encoding === 'UTF-8') {
4480 43
            $str_part_two = (string) \mb_substr($str, 1);
4481
4482 43
            if ($use_mb_functions) {
4483 43
                $str_part_one = \mb_strtolower(
4484 43
                    (string) \mb_substr($str, 0, 1)
4485
                );
4486
            } else {
4487
                $str_part_one = self::strtolower(
4488
                    (string) \mb_substr($str, 0, 1),
4489
                    $encoding,
4490
                    false,
4491
                    $lang,
4492 43
                    $try_to_keep_the_string_length
4493
                );
4494
            }
4495
        } else {
4496 3
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
4497
4498 3
            $str_part_two = (string) self::substr($str, 1, null, $encoding);
4499
4500 3
            $str_part_one = self::strtolower(
4501 3
                (string) self::substr($str, 0, 1, $encoding),
4502 3
                $encoding,
4503 3
                false,
4504 3
                $lang,
4505 3
                $try_to_keep_the_string_length
4506
            );
4507
        }
4508
4509 46
        return $str_part_one . $str_part_two;
4510
    }
4511
4512
    /**
4513
     * alias for "UTF8::lcfirst()"
4514
     *
4515
     * @param string      $str
4516
     * @param string      $encoding
4517
     * @param bool        $clean_utf8
4518
     * @param string|null $lang
4519
     * @param bool        $try_to_keep_the_string_length
4520
     *
4521
     * @psalm-pure
4522
     *
4523
     * @return string
4524
     *
4525
     * @see        UTF8::lcfirst()
4526
     * @deprecated <p>please use "UTF8::lcfirst()"</p>
4527
     */
4528 2
    public static function lcword(
4529
        string $str,
4530
        string $encoding = 'UTF-8',
4531
        bool $clean_utf8 = false,
4532
        string $lang = null,
4533
        bool $try_to_keep_the_string_length = false
4534
    ): string {
4535 2
        return self::lcfirst(
4536 2
            $str,
4537 2
            $encoding,
4538 2
            $clean_utf8,
4539 2
            $lang,
4540 2
            $try_to_keep_the_string_length
4541
        );
4542
    }
4543
4544
    /**
4545
     * Lowercase for all words in the string.
4546
     *
4547
     * @param string      $str                           <p>The input string.</p>
4548
     * @param string[]    $exceptions                    [optional] <p>Exclusion for some words.</p>
4549
     * @param string      $char_list                     [optional] <p>Additional chars that contains to words and do
4550
     *                                                   not start a new word.</p>
4551
     * @param string      $encoding                      [optional] <p>Set the charset.</p>
4552
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
4553
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
4554
     *                                                   tr</p>
4555
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ
4556
     *                                                   -> ß</p>
4557
     *
4558
     * @psalm-pure
4559
     *
4560
     * @return string
4561
     */
4562 2
    public static function lcwords(
4563
        string $str,
4564
        array $exceptions = [],
4565
        string $char_list = '',
4566
        string $encoding = 'UTF-8',
4567
        bool $clean_utf8 = false,
4568
        string $lang = null,
4569
        bool $try_to_keep_the_string_length = false
4570
    ): string {
4571 2
        if (!$str) {
4572 2
            return '';
4573
        }
4574
4575 2
        $words = self::str_to_words($str, $char_list);
4576 2
        $use_exceptions = $exceptions !== [];
4577
4578 2
        $words_str = '';
4579 2
        foreach ($words as &$word) {
4580 2
            if (!$word) {
4581 2
                continue;
4582
            }
4583
4584
            if (
4585 2
                !$use_exceptions
4586
                ||
4587 2
                !\in_array($word, $exceptions, true)
4588
            ) {
4589 2
                $words_str .= self::lcfirst($word, $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length);
4590
            } else {
4591 2
                $words_str .= $word;
4592
            }
4593
        }
4594
4595 2
        return $words_str;
4596
    }
4597
4598
    /**
4599
     * alias for "UTF8::lcfirst()"
4600
     *
4601
     * @param string      $str
4602
     * @param string      $encoding
4603
     * @param bool        $clean_utf8
4604
     * @param string|null $lang
4605
     * @param bool        $try_to_keep_the_string_length
4606
     *
4607
     * @psalm-pure
4608
     *
4609
     * @return string
4610
     *
4611
     * @see        UTF8::lcfirst()
4612
     * @deprecated <p>please use "UTF8::lcfirst()"</p>
4613
     */
4614 5
    public static function lowerCaseFirst(
4615
        string $str,
4616
        string $encoding = 'UTF-8',
4617
        bool $clean_utf8 = false,
4618
        string $lang = null,
4619
        bool $try_to_keep_the_string_length = false
4620
    ): string {
4621 5
        return self::lcfirst(
4622 5
            $str,
4623 5
            $encoding,
4624 5
            $clean_utf8,
4625 5
            $lang,
4626 5
            $try_to_keep_the_string_length
4627
        );
4628
    }
4629
4630
    /**
4631
     * Strip whitespace or other characters from the beginning of a UTF-8 string.
4632
     *
4633
     * EXAMPLE: <code>UTF8::ltrim(' 中文空白  '); // '中文空白  '</code>
4634
     *
4635
     * @param string      $str   <p>The string to be trimmed</p>
4636
     * @param string|null $chars <p>Optional characters to be stripped</p>
4637
     *
4638
     * @psalm-pure
4639
     *
4640
     * @return string the string with unwanted characters stripped from the left
4641
     */
4642 23
    public static function ltrim(string $str = '', string $chars = null): string
4643
    {
4644 23
        if ($str === '') {
4645 3
            return '';
4646
        }
4647
4648 22
        if (self::$SUPPORT['mbstring'] === true) {
4649 22
            if ($chars !== null) {
4650
                /** @noinspection PregQuoteUsageInspection */
4651 11
                $chars = \preg_quote($chars);
4652 11
                $pattern = "^[${chars}]+";
4653
            } else {
4654 14
                $pattern = '^[\\s]+';
4655
            }
4656
4657
            /** @noinspection PhpComposerExtensionStubsInspection */
4658 22
            return (string) \mb_ereg_replace($pattern, '', $str);
4659
        }
4660
4661
        if ($chars !== null) {
4662
            $chars = \preg_quote($chars, '/');
4663
            $pattern = "^[${chars}]+";
4664
        } else {
4665
            $pattern = '^[\\s]+';
4666
        }
4667
4668
        return self::regex_replace($str, $pattern, '');
4669
    }
4670
4671
    /**
4672
     * Returns the UTF-8 character with the maximum code point in the given data.
4673
     *
4674
     * EXAMPLE: <code>UTF8::max('abc-äöü-中文空白'); // 'ø'</code>
4675
     *
4676
     * @param array<string>|string $arg <p>A UTF-8 encoded string or an array of such strings.</p>
4677
     *
4678
     * @psalm-pure
4679
     *
4680
     * @return string|null the character with the highest code point than others, returns null on failure or empty input
4681
     */
4682
    public static function max($arg)
4683
    {
4684 2
        if (\is_array($arg)) {
4685 2
            $arg = \implode('', $arg);
4686
        }
4687
4688 2
        $codepoints = self::codepoints($arg);
4689 2
        if ($codepoints === []) {
4690 2
            return null;
4691
        }
4692
4693 2
        $codepoint_max = \max($codepoints);
4694
4695 2
        return self::chr((int) $codepoint_max);
4696
    }
4697
4698
    /**
4699
     * Calculates and returns the maximum number of bytes taken by any
4700
     * UTF-8 encoded character in the given string.
4701
     *
4702
     * EXAMPLE: <code>UTF8::max_chr_width('Intërnâtiônàlizætiøn'); // 2</code>
4703
     *
4704
     * @param string $str <p>The original Unicode string.</p>
4705
     *
4706
     * @psalm-pure
4707
     *
4708
     * @return int
4709
     *             <p>Max byte lengths of the given chars.</p>
4710
     */
4711
    public static function max_chr_width(string $str): int
4712
    {
4713 2
        $bytes = self::chr_size_list($str);
4714 2
        if ($bytes !== []) {
4715 2
            return (int) \max($bytes);
4716
        }
4717
4718 2
        return 0;
4719
    }
4720
4721
    /**
4722
     * Checks whether mbstring is available on the server.
4723
     *
4724
     * @psalm-pure
4725
     *
4726
     * @return bool
4727
     *              <p><strong>true</strong> if available, <strong>false</strong> otherwise</p>
4728
     *
4729
     * @internal <p>Please do not use it anymore, we will make is private in next major version.</p>
4730
     */
4731
    public static function mbstring_loaded(): bool
4732
    {
4733 28
        return \extension_loaded('mbstring');
4734
    }
4735
4736
    /**
4737
     * Returns the UTF-8 character with the minimum code point in the given data.
4738
     *
4739
     * EXAMPLE: <code>UTF8::min('abc-äöü-中文空白'); // '-'</code>
4740
     *
4741
     * @param string|string[] $arg <strong>A UTF-8 encoded string or an array of such strings.</strong>
4742
     *
4743
     * @psalm-pure
4744
     *
4745
     * @return string|null
4746
     *                     <p>The character with the lowest code point than others, returns null on failure or empty input.</p>
4747
     */
4748
    public static function min($arg)
4749
    {
4750 2
        if (\is_array($arg)) {
4751 2
            $arg = \implode('', $arg);
4752
        }
4753
4754 2
        $codepoints = self::codepoints($arg);
4755 2
        if ($codepoints === []) {
4756 2
            return null;
4757
        }
4758
4759 2
        $codepoint_min = \min($codepoints);
4760
4761 2
        return self::chr((int) $codepoint_min);
4762
    }
4763
4764
    /**
4765
     * alias for "UTF8::normalize_encoding()"
4766
     *
4767
     * @param mixed $encoding
4768
     * @param mixed $fallback
4769
     *
4770
     * @psalm-pure
4771
     *
4772
     * @return mixed
4773
     *
4774
     * @see        UTF8::normalize_encoding()
4775
     * @deprecated <p>please use "UTF8::normalize_encoding()"</p>
4776
     */
4777
    public static function normalizeEncoding($encoding, $fallback = '')
4778
    {
4779 2
        return self::normalize_encoding($encoding, $fallback);
4780
    }
4781
4782
    /**
4783
     * Normalize the encoding-"name" input.
4784
     *
4785
     * EXAMPLE: <code>UTF8::normalize_encoding('UTF8'); // 'UTF-8'</code>
4786
     *
4787
     * @param mixed $encoding <p>e.g.: ISO, UTF8, WINDOWS-1251 etc.</p>
4788
     * @param mixed $fallback <p>e.g.: UTF-8</p>
4789
     *
4790
     * @psalm-pure
4791
     *
4792
     * @return mixed|string
4793
     *                      <p>e.g.: ISO-8859-1, UTF-8, WINDOWS-1251 etc.<br>Will return a empty string as fallback (by default)</p>
4794
     *
4795
     * @template TNormalizeEncodingFallback
4796
     * @phpstan-param string|TNormalizeEncodingFallback $fallback
4797
     * @phpstan-return string|TNormalizeEncodingFallback
4798
     */
4799
    public static function normalize_encoding($encoding, $fallback = '')
4800
    {
4801
        /**
4802
         * @psalm-suppress ImpureStaticVariable
4803
         *
4804
         * @var array<string,string>
4805
         */
4806 339
        static $STATIC_NORMALIZE_ENCODING_CACHE = [];
4807
4808
        // init
4809 339
        $encoding = (string) $encoding;
4810
4811 339
        if (!$encoding) {
4812 290
            return $fallback;
4813
        }
4814
4815
        if (
4816 53
            $encoding === 'UTF-8'
4817
            ||
4818 53
            $encoding === 'UTF8'
4819
        ) {
4820 29
            return 'UTF-8';
4821
        }
4822
4823
        if (
4824 44
            $encoding === '8BIT'
4825
            ||
4826 44
            $encoding === 'BINARY'
4827
        ) {
4828
            return 'CP850';
4829
        }
4830
4831
        if (
4832 44
            $encoding === 'HTML'
4833
            ||
4834 44
            $encoding === 'HTML-ENTITIES'
4835
        ) {
4836 2
            return 'HTML-ENTITIES';
4837
        }
4838
4839
        if (
4840 44
            $encoding === 'ISO'
4841
            ||
4842 44
            $encoding === 'ISO-8859-1'
4843
        ) {
4844 41
            return 'ISO-8859-1';
4845
        }
4846
4847
        if (
4848 11
            $encoding === '1' // only a fallback, for non "strict_types" usage ...
4849
            ||
4850 11
            $encoding === '0' // only a fallback, for non "strict_types" usage ...
4851
        ) {
4852
            return $fallback;
4853
        }
4854
4855 11
        if (isset($STATIC_NORMALIZE_ENCODING_CACHE[$encoding])) {
4856 8
            return $STATIC_NORMALIZE_ENCODING_CACHE[$encoding];
4857
        }
4858
4859 5
        if (self::$ENCODINGS === null) {
4860 1
            self::$ENCODINGS = self::getData('encodings');
4861
        }
4862
4863 5
        if (\in_array($encoding, self::$ENCODINGS, true)) {
4864 3
            $STATIC_NORMALIZE_ENCODING_CACHE[$encoding] = $encoding;
4865
4866 3
            return $encoding;
4867
        }
4868
4869 4
        $encoding_original = $encoding;
4870 4
        $encoding = \strtoupper($encoding);
4871 4
        $encoding_upper_helper = (string) \preg_replace('/[^a-zA-Z0-9]/u', '', $encoding);
4872
4873
        $equivalences = [
4874 4
            'ISO8859'     => 'ISO-8859-1',
4875
            'ISO88591'    => 'ISO-8859-1',
4876
            'ISO'         => 'ISO-8859-1',
4877
            'LATIN'       => 'ISO-8859-1',
4878
            'LATIN1'      => 'ISO-8859-1', // Western European
4879
            'ISO88592'    => 'ISO-8859-2',
4880
            'LATIN2'      => 'ISO-8859-2', // Central European
4881
            'ISO88593'    => 'ISO-8859-3',
4882
            'LATIN3'      => 'ISO-8859-3', // Southern European
4883
            'ISO88594'    => 'ISO-8859-4',
4884
            'LATIN4'      => 'ISO-8859-4', // Northern European
4885
            'ISO88595'    => 'ISO-8859-5',
4886
            'ISO88596'    => 'ISO-8859-6', // Greek
4887
            'ISO88597'    => 'ISO-8859-7',
4888
            'ISO88598'    => 'ISO-8859-8', // Hebrew
4889
            'ISO88599'    => 'ISO-8859-9',
4890
            'LATIN5'      => 'ISO-8859-9', // Turkish
4891
            'ISO885911'   => 'ISO-8859-11',
4892
            'TIS620'      => 'ISO-8859-11', // Thai
4893
            'ISO885910'   => 'ISO-8859-10',
4894
            'LATIN6'      => 'ISO-8859-10', // Nordic
4895
            'ISO885913'   => 'ISO-8859-13',
4896
            'LATIN7'      => 'ISO-8859-13', // Baltic
4897
            'ISO885914'   => 'ISO-8859-14',
4898
            'LATIN8'      => 'ISO-8859-14', // Celtic
4899
            'ISO885915'   => 'ISO-8859-15',
4900
            'LATIN9'      => 'ISO-8859-15', // Western European (with some extra chars e.g. €)
4901
            'ISO885916'   => 'ISO-8859-16',
4902
            'LATIN10'     => 'ISO-8859-16', // Southeast European
4903
            'CP1250'      => 'WINDOWS-1250',
4904
            'WIN1250'     => 'WINDOWS-1250',
4905
            'WINDOWS1250' => 'WINDOWS-1250',
4906
            'CP1251'      => 'WINDOWS-1251',
4907
            'WIN1251'     => 'WINDOWS-1251',
4908
            'WINDOWS1251' => 'WINDOWS-1251',
4909
            'CP1252'      => 'WINDOWS-1252',
4910
            'WIN1252'     => 'WINDOWS-1252',
4911
            'WINDOWS1252' => 'WINDOWS-1252',
4912
            'CP1253'      => 'WINDOWS-1253',
4913
            'WIN1253'     => 'WINDOWS-1253',
4914
            'WINDOWS1253' => 'WINDOWS-1253',
4915
            'CP1254'      => 'WINDOWS-1254',
4916
            'WIN1254'     => 'WINDOWS-1254',
4917
            'WINDOWS1254' => 'WINDOWS-1254',
4918
            'CP1255'      => 'WINDOWS-1255',
4919
            'WIN1255'     => 'WINDOWS-1255',
4920
            'WINDOWS1255' => 'WINDOWS-1255',
4921
            'CP1256'      => 'WINDOWS-1256',
4922
            'WIN1256'     => 'WINDOWS-1256',
4923
            'WINDOWS1256' => 'WINDOWS-1256',
4924
            'CP1257'      => 'WINDOWS-1257',
4925
            'WIN1257'     => 'WINDOWS-1257',
4926
            'WINDOWS1257' => 'WINDOWS-1257',
4927
            'CP1258'      => 'WINDOWS-1258',
4928
            'WIN1258'     => 'WINDOWS-1258',
4929
            'WINDOWS1258' => 'WINDOWS-1258',
4930
            'UTF16'       => 'UTF-16',
4931
            'UTF32'       => 'UTF-32',
4932
            'UTF8'        => 'UTF-8',
4933
            'UTF'         => 'UTF-8',
4934
            'UTF7'        => 'UTF-7',
4935
            '8BIT'        => 'CP850',
4936
            'BINARY'      => 'CP850',
4937
        ];
4938
4939 4
        if (!empty($equivalences[$encoding_upper_helper])) {
4940 3
            $encoding = $equivalences[$encoding_upper_helper];
4941
        }
4942
4943 4
        $STATIC_NORMALIZE_ENCODING_CACHE[$encoding_original] = $encoding;
4944
4945 4
        return $encoding;
4946
    }
4947
4948
    /**
4949
     * Standardize line ending to unix-like.
4950
     *
4951
     * @param string          $str      <p>The input string.</p>
4952
     * @param string|string[] $replacer <p>The replacer char e.g. "\n" (Linux) or "\r\n" (Windows). You can also use \PHP_EOL
4953
     *                                  here.</p>
4954
     *
4955
     * @psalm-pure
4956
     *
4957
     * @return string
4958
     *                <p>A string with normalized line ending.</p>
4959
     */
4960
    public static function normalize_line_ending(string $str, $replacer = "\n"): string
4961
    {
4962 5
        return \str_replace(["\r\n", "\r", "\n"], $replacer, $str);
4963
    }
4964
4965
    /**
4966
     * Normalize some MS Word special characters.
4967
     *
4968
     * EXAMPLE: <code>UTF8::normalize_msword('„Abcdef…”'); // '"Abcdef..."'</code>
4969
     *
4970
     * @param string $str <p>The string to be normalized.</p>
4971
     *
4972
     * @psalm-pure
4973
     *
4974
     * @return string
4975
     *                <p>A string with normalized characters for commonly used chars in Word documents.</p>
4976
     */
4977
    public static function normalize_msword(string $str): string
4978
    {
4979 10
        return ASCII::normalize_msword($str);
4980
    }
4981
4982
    /**
4983
     * Normalize the whitespace.
4984
     *
4985
     * EXAMPLE: <code>UTF8::normalize_whitespace("abc-\xc2\xa0-öäü-\xe2\x80\xaf-\xE2\x80\xAC", true); // "abc-\xc2\xa0-öäü- -"</code>
4986
     *
4987
     * @param string $str                        <p>The string to be normalized.</p>
4988
     * @param bool   $keep_non_breaking_space    [optional] <p>Set to true, to keep non-breaking-spaces.</p>
4989
     * @param bool   $keep_bidi_unicode_controls [optional] <p>Set to true, to keep non-printable (for the web)
4990
     *                                           bidirectional text chars.</p>
4991
     *
4992
     * @psalm-pure
4993
     *
4994
     * @return string
4995
     *                <p>A string with normalized whitespace.</p>
4996
     */
4997
    public static function normalize_whitespace(
4998
        string $str,
4999
        bool $keep_non_breaking_space = false,
5000
        bool $keep_bidi_unicode_controls = false
5001
    ): string {
5002 61
        return ASCII::normalize_whitespace(
5003 61
            $str,
5004 61
            $keep_non_breaking_space,
5005 61
            $keep_bidi_unicode_controls
5006
        );
5007
    }
5008
5009
    /**
5010
     * Calculates Unicode code point of the given UTF-8 encoded character.
5011
     *
5012
     * INFO: opposite to UTF8::chr()
5013
     *
5014
     * EXAMPLE: <code>UTF8::ord('☃'); // 0x2603</code>
5015
     *
5016
     * @param string $chr      <p>The character of which to calculate code point.<p/>
5017
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
5018
     *
5019
     * @psalm-pure
5020
     *
5021
     * @return int
5022
     *             <p>Unicode code point of the given character,<br>
5023
     *             0 on invalid UTF-8 byte sequence</p>
5024
     */
5025
    public static function ord($chr, string $encoding = 'UTF-8'): int
5026
    {
5027
        /**
5028
         * @psalm-suppress ImpureStaticVariable
5029
         *
5030
         * @var array<string,int>
5031
         */
5032 27
        static $CHAR_CACHE = [];
5033
5034
        // init
5035 27
        $chr = (string) $chr;
5036
5037 27
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
5038 5
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
5039
        }
5040
5041 27
        $cache_key = $chr . '_' . $encoding;
5042 27
        if (isset($CHAR_CACHE[$cache_key])) {
5043 27
            return $CHAR_CACHE[$cache_key];
5044
        }
5045
5046
        // check again, if it's still not UTF-8
5047 11
        if ($encoding !== 'UTF-8') {
5048 3
            $chr = self::encode($encoding, $chr);
5049
        }
5050
5051 11
        if (self::$ORD === null) {
5052
            self::$ORD = self::getData('ord');
5053
        }
5054
5055 11
        if (isset(self::$ORD[$chr])) {
5056 11
            return $CHAR_CACHE[$cache_key] = self::$ORD[$chr];
5057
        }
5058
5059
        //
5060
        // fallback via "IntlChar"
5061
        //
5062
5063 6
        if (self::$SUPPORT['intlChar'] === true) {
5064
            /** @noinspection PhpComposerExtensionStubsInspection */
5065 5
            $code = \IntlChar::ord($chr);
5066 5
            if ($code) {
5067 5
                return $CHAR_CACHE[$cache_key] = $code;
5068
            }
5069
        }
5070
5071
        //
5072
        // fallback via vanilla php
5073
        //
5074
5075
        /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
5076 1
        $chr = \unpack('C*', (string) \substr($chr, 0, 4));
5077
        /** @noinspection OffsetOperationsInspection */
5078 1
        $code = $chr ? $chr[1] : 0;
5079
5080
        /** @noinspection OffsetOperationsInspection */
5081 1
        if ($code >= 0xF0 && isset($chr[4])) {
5082
            /** @noinspection UnnecessaryCastingInspection */
5083
            /** @noinspection OffsetOperationsInspection */
5084
            return $CHAR_CACHE[$cache_key] = (int) ((($code - 0xF0) << 18) + (($chr[2] - 0x80) << 12) + (($chr[3] - 0x80) << 6) + $chr[4] - 0x80);
5085
        }
5086
5087
        /** @noinspection OffsetOperationsInspection */
5088 1
        if ($code >= 0xE0 && isset($chr[3])) {
5089
            /** @noinspection UnnecessaryCastingInspection */
5090
            /** @noinspection OffsetOperationsInspection */
5091 1
            return $CHAR_CACHE[$cache_key] = (int) ((($code - 0xE0) << 12) + (($chr[2] - 0x80) << 6) + $chr[3] - 0x80);
5092
        }
5093
5094
        /** @noinspection OffsetOperationsInspection */
5095 1
        if ($code >= 0xC0 && isset($chr[2])) {
5096
            /** @noinspection UnnecessaryCastingInspection */
5097
            /** @noinspection OffsetOperationsInspection */
5098 1
            return $CHAR_CACHE[$cache_key] = (int) ((($code - 0xC0) << 6) + $chr[2] - 0x80);
5099
        }
5100
5101
        return $CHAR_CACHE[$cache_key] = $code;
5102
    }
5103
5104
    /**
5105
     * Parses the string into an array (into the the second parameter).
5106
     *
5107
     * WARNING: Unlike "parse_str()", this method does not (re-)place variables in the current scope,
5108
     *          if the second parameter is not set!
5109
     *
5110
     * EXAMPLE: <code>
5111
     * UTF8::parse_str('Iñtërnâtiônéàlizætiøn=測試&arr[]=foo+測試&arr[]=ການທົດສອບ', $array);
5112
     * echo $array['Iñtërnâtiônéàlizætiøn']; // '測試'
5113
     * </code>
5114
     *
5115
     * @see http://php.net/manual/en/function.parse-str.php
5116
     *
5117
     * @param string $str        <p>The input string.</p>
5118
     * @param array  $result     <p>The result will be returned into this reference parameter.</p>
5119
     * @param bool   $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
5120
     *
5121
     * @psalm-pure
5122
     *
5123
     * @return bool
5124
     *              <p>Will return <strong>false</strong> if php can't parse the string and we haven't any $result.</p>
5125
     */
5126
    public static function parse_str(string $str, &$result, bool $clean_utf8 = false): bool
5127
    {
5128 2
        if ($clean_utf8) {
5129 2
            $str = self::clean($str);
5130
        }
5131
5132 2
        if (self::$SUPPORT['mbstring'] === true) {
5133 2
            $return = \mb_parse_str($str, $result);
5134
5135 2
            return $return !== false && $result !== [];
5136
        }
5137
5138
        /**
5139
         * @psalm-suppress ImpureFunctionCall - we use the second parameter, so we don't change variables by magic
5140
         */
5141
        \parse_str($str, $result);
5142
5143
        return $result !== [];
5144
    }
5145
5146
    /**
5147
     * Checks if \u modifier is available that enables Unicode support in PCRE.
5148
     *
5149
     * @psalm-pure
5150
     *
5151
     * @return bool
5152
     *              <p>
5153
     *              <strong>true</strong> if support is available,<br>
5154
     *              <strong>false</strong> otherwise
5155
     *              </p>
5156
     */
5157
    public static function pcre_utf8_support(): bool
5158
    {
5159
        /** @noinspection PhpUsageOfSilenceOperatorInspection */
5160
        return (bool) @\preg_match('//u', '');
5161
    }
5162
5163
    /**
5164
     * Create an array containing a range of UTF-8 characters.
5165
     *
5166
     * EXAMPLE: <code>UTF8::range('κ', 'ζ'); // array('κ', 'ι', 'θ', 'η', 'ζ',)</code>
5167
     *
5168
     * @param int|string $var1      <p>Numeric or hexadecimal code points, or a UTF-8 character to start from.</p>
5169
     * @param int|string $var2      <p>Numeric or hexadecimal code points, or a UTF-8 character to end at.</p>
5170
     * @param bool       $use_ctype <p>use ctype to detect numeric and hexadecimal, otherwise we will use a simple
5171
     *                              "is_numeric"</p>
5172
     * @param string     $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
5173
     * @param float|int  $step      [optional] <p>
5174
     *                              If a step value is given, it will be used as the
5175
     *                              increment between elements in the sequence. step
5176
     *                              should be given as a positive number. If not specified,
5177
     *                              step will default to 1.
5178
     *                              </p>
5179
     *
5180
     * @psalm-pure
5181
     *
5182
     * @return string[]
5183
     */
5184
    public static function range(
5185
        $var1,
5186
        $var2,
5187
        bool $use_ctype = true,
5188
        string $encoding = 'UTF-8',
5189
        $step = 1
5190
    ): array {
5191 2
        if (!$var1 || !$var2) {
5192 2
            return [];
5193
        }
5194
5195 2
        if ($step !== 1) {
5196
            /**
5197
             * @psalm-suppress RedundantConditionGivenDocblockType
5198
             * @psalm-suppress DocblockTypeContradiction
5199
             */
5200 1
            if (!\is_numeric($step)) {
0 ignored issues
show
introduced by
The condition is_numeric($step) is always true.
Loading history...
5201
                throw new \InvalidArgumentException('$step need to be a number, type given: ' . \gettype($step));
5202
            }
5203
5204
            /**
5205
             * @psalm-suppress RedundantConditionGivenDocblockType - false-positive from psalm?
5206
             */
5207 1
            if ($step <= 0) {
5208
                throw new \InvalidArgumentException('$step need to be a positive number, given: ' . $step);
5209
            }
5210
        }
5211
5212 2
        if ($use_ctype && self::$SUPPORT['ctype'] === false) {
5213
            throw new \RuntimeException('ext-ctype: is not installed');
5214
        }
5215
5216 2
        $is_digit = false;
5217 2
        $is_xdigit = false;
5218
5219
        /** @noinspection PhpComposerExtensionStubsInspection */
5220 2
        if ($use_ctype && \ctype_digit((string) $var1) && \ctype_digit((string) $var2)) {
5221 2
            $is_digit = true;
5222 2
            $start = (int) $var1;
5223 2
        } /** @noinspection PhpComposerExtensionStubsInspection */ elseif ($use_ctype && \ctype_xdigit($var1) && \ctype_xdigit($var2)) {
5224
            $is_xdigit = true;
5225
            $start = (int) self::hex_to_int((string) $var1);
5226 2
        } elseif (!$use_ctype && \is_numeric($var1)) {
5227 1
            $start = (int) $var1;
5228
        } else {
5229 2
            $start = self::ord((string) $var1);
5230
        }
5231
5232 2
        if (!$start) {
5233
            return [];
5234
        }
5235
5236 2
        if ($is_digit) {
5237 2
            $end = (int) $var2;
5238 2
        } elseif ($is_xdigit) {
5239
            $end = (int) self::hex_to_int((string) $var2);
5240 2
        } elseif (!$use_ctype && \is_numeric($var2)) {
5241 1
            $end = (int) $var2;
5242
        } else {
5243 2
            $end = self::ord((string) $var2);
5244
        }
5245
5246 2
        if (!$end) {
5247
            return [];
5248
        }
5249
5250 2
        $array = [];
5251 2
        foreach (\range($start, $end, $step) as $i) {
5252 2
            $array[] = (string) self::chr((int) $i, $encoding);
5253
        }
5254
5255 2
        return $array;
5256
    }
5257
5258
    /**
5259
     * Multi decode HTML entity + fix urlencoded-win1252-chars.
5260
     *
5261
     * EXAMPLE: <code>UTF8::rawurldecode('tes%20öäü%20\u00edtest+test'); // 'tes öäü ítest+test'</code>
5262
     *
5263
     * e.g:
5264
     * 'test+test'                     => 'test+test'
5265
     * 'D&#252;sseldorf'               => 'Düsseldorf'
5266
     * 'D%FCsseldorf'                  => 'Düsseldorf'
5267
     * 'D&#xFC;sseldorf'               => 'Düsseldorf'
5268
     * 'D%26%23xFC%3Bsseldorf'         => 'Düsseldorf'
5269
     * 'Düsseldorf'                   => 'Düsseldorf'
5270
     * 'D%C3%BCsseldorf'               => 'Düsseldorf'
5271
     * 'D%C3%83%C2%BCsseldorf'         => 'Düsseldorf'
5272
     * 'D%25C3%2583%25C2%25BCsseldorf' => 'Düsseldorf'
5273
     *
5274
     * @param string $str          <p>The input string.</p>
5275
     * @param bool   $multi_decode <p>Decode as often as possible.</p>
5276
     *
5277
     * @psalm-pure
5278
     *
5279
     * @return string
5280
     *                <p>The decoded URL, as a string.</p>
5281
     */
5282
    public static function rawurldecode(string $str, bool $multi_decode = true): string
5283
    {
5284 7
        if ($str === '') {
5285 4
            return '';
5286
        }
5287
5288
        if (
5289 7
            \strpos($str, '&') === false
5290
            &&
5291 7
            \strpos($str, '%') === false
5292
            &&
5293 7
            \strpos($str, '+') === false
5294
            &&
5295 7
            \strpos($str, '\u') === false
5296
        ) {
5297 4
            return self::fix_simple_utf8($str);
5298
        }
5299
5300 7
        $str = self::urldecode_unicode_helper($str);
5301
5302 7
        if ($multi_decode) {
5303
            do {
5304 6
                $str_compare = $str;
5305
5306
                /**
5307
                 * @psalm-suppress PossiblyInvalidArgument
5308
                 */
5309 6
                $str = self::fix_simple_utf8(
5310 6
                    \rawurldecode(
5311 6
                        self::html_entity_decode(
5312 6
                            self::to_utf8($str),
5313 6
                            \ENT_QUOTES | \ENT_HTML5
5314
                        )
5315
                    )
5316
                );
5317 6
            } while ($str_compare !== $str);
5318
        } else {
5319
            /**
5320
             * @psalm-suppress PossiblyInvalidArgument
5321
             */
5322 1
            $str = self::fix_simple_utf8(
5323 1
                \rawurldecode(
5324 1
                    self::html_entity_decode(
5325 1
                        self::to_utf8($str),
5326 1
                        \ENT_QUOTES | \ENT_HTML5
5327
                    )
5328
                )
5329
            );
5330
        }
5331
5332 7
        return $str;
5333
    }
5334
5335
    /**
5336
     * Replaces all occurrences of $pattern in $str by $replacement.
5337
     *
5338
     * @param string $str         <p>The input string.</p>
5339
     * @param string $pattern     <p>The regular expression pattern.</p>
5340
     * @param string $replacement <p>The string to replace with.</p>
5341
     * @param string $options     [optional] <p>Matching conditions to be used.</p>
5342
     * @param string $delimiter   [optional] <p>Delimiter the the regex. Default: '/'</p>
5343
     *
5344
     * @psalm-pure
5345
     *
5346
     * @return string
5347
     */
5348
    public static function regex_replace(
5349
        string $str,
5350
        string $pattern,
5351
        string $replacement,
5352
        string $options = '',
5353
        string $delimiter = '/'
5354
    ): string {
5355 18
        if ($options === 'msr') {
5356 9
            $options = 'ms';
5357
        }
5358
5359
        // fallback
5360 18
        if (!$delimiter) {
5361
            $delimiter = '/';
5362
        }
5363
5364 18
        return (string) \preg_replace(
5365 18
            $delimiter . $pattern . $delimiter . 'u' . $options,
5366 18
            $replacement,
5367 18
            $str
5368
        );
5369
    }
5370
5371
    /**
5372
     * alias for "UTF8::remove_bom()"
5373
     *
5374
     * @param string $str
5375
     *
5376
     * @psalm-pure
5377
     *
5378
     * @return string
5379
     *
5380
     * @see        UTF8::remove_bom()
5381
     * @deprecated <p>please use "UTF8::remove_bom()"</p>
5382
     */
5383
    public static function removeBOM(string $str): string
5384
    {
5385 1
        return self::remove_bom($str);
5386
    }
5387
5388
    /**
5389
     * Remove the BOM from UTF-8 / UTF-16 / UTF-32 strings.
5390
     *
5391
     * EXAMPLE: <code>UTF8::remove_bom("\xEF\xBB\xBFΜπορώ να"); // 'Μπορώ να'</code>
5392
     *
5393
     * @param string $str <p>The input string.</p>
5394
     *
5395
     * @psalm-pure
5396
     *
5397
     * @return string
5398
     *                <p>A string without UTF-BOM.</p>
5399
     */
5400
    public static function remove_bom(string $str): string
5401
    {
5402 55
        if ($str === '') {
5403 9
            return '';
5404
        }
5405
5406 55
        $str_length = \strlen($str);
5407 55
        foreach (self::$BOM as $bom_string => $bom_byte_length) {
5408 55
            if (\strncmp($str, $bom_string, $bom_byte_length) === 0) {
5409
                /** @var false|string $str_tmp - needed for PhpStan (stubs error) */
5410 11
                $str_tmp = \substr($str, $bom_byte_length, $str_length);
5411 11
                if ($str_tmp === false) {
5412
                    return '';
5413
                }
5414
5415 11
                $str_length -= (int) $bom_byte_length;
5416
5417 55
                $str = (string) $str_tmp;
5418
            }
5419
        }
5420
5421 55
        return $str;
5422
    }
5423
5424
    /**
5425
     * Removes duplicate occurrences of a string in another string.
5426
     *
5427
     * EXAMPLE: <code>UTF8::remove_duplicates('öäü-κόσμεκόσμε-äöü', 'κόσμε'); // 'öäü-κόσμε-äöü'</code>
5428
     *
5429
     * @param string          $str  <p>The base string.</p>
5430
     * @param string|string[] $what <p>String to search for in the base string.</p>
5431
     *
5432
     * @psalm-pure
5433
     *
5434
     * @return string
5435
     *                <p>A string with removed duplicates.</p>
5436
     */
5437
    public static function remove_duplicates(string $str, $what = ' '): string
5438
    {
5439 2
        if (\is_string($what)) {
5440 2
            $what = [$what];
5441
        }
5442
5443
        /**
5444
         * @psalm-suppress RedundantConditionGivenDocblockType
5445
         */
5446 2
        if (\is_array($what)) {
0 ignored issues
show
introduced by
The condition is_array($what) is always true.
Loading history...
5447 2
            foreach ($what as $item) {
5448 2
                $str = (string) \preg_replace('/(' . \preg_quote($item, '/') . ')+/u', $item, $str);
5449
            }
5450
        }
5451
5452 2
        return $str;
5453
    }
5454
5455
    /**
5456
     * Remove html via "strip_tags()" from the string.
5457
     *
5458
     * @param string $str            <p>The input string.</p>
5459
     * @param string $allowable_tags [optional] <p>You can use the optional second parameter to specify tags which
5460
     *                               should not be stripped. Default: null
5461
     *                               </p>
5462
     *
5463
     * @psalm-pure
5464
     *
5465
     * @return string
5466
     *                <p>A string with without html tags.</p>
5467
     */
5468
    public static function remove_html(string $str, string $allowable_tags = ''): string
5469
    {
5470 6
        return \strip_tags($str, $allowable_tags);
5471
    }
5472
5473
    /**
5474
     * Remove all breaks [<br> | \r\n | \r | \n | ...] from the string.
5475
     *
5476
     * @param string $str         <p>The input string.</p>
5477
     * @param string $replacement [optional] <p>Default is a empty string.</p>
5478
     *
5479
     * @psalm-pure
5480
     *
5481
     * @return string
5482
     *                <p>A string without breaks.</p>
5483
     */
5484
    public static function remove_html_breaks(string $str, string $replacement = ''): string
5485
    {
5486 6
        return (string) \preg_replace("#/\r\n|\r|\n|<br.*/?>#isU", $replacement, $str);
5487
    }
5488
5489
    /**
5490
     * Remove invisible characters from a string.
5491
     *
5492
     * e.g.: This prevents sandwiching null characters between ascii characters, like Java\0script.
5493
     *
5494
     * EXAMPLE: <code>UTF8::remove_invisible_characters("κόσ\0με"); // 'κόσμε'</code>
5495
     *
5496
     * copy&past from https://github.com/bcit-ci/CodeIgniter/blob/develop/system/core/Common.php
5497
     *
5498
     * @param string $str         <p>The input string.</p>
5499
     * @param bool   $url_encoded [optional] <p>
5500
     *                            Try to remove url encoded control character.
5501
     *                            WARNING: maybe contains false-positives e.g. aa%0Baa -> aaaa.
5502
     *                            <br>
5503
     *                            Default: false
5504
     *                            </p>
5505
     * @param string $replacement [optional] <p>The replacement character.</p>
5506
     *
5507
     * @psalm-pure
5508
     *
5509
     * @return string
5510
     *                <p>A string without invisible chars.</p>
5511
     */
5512
    public static function remove_invisible_characters(
5513
        string $str,
5514
        bool $url_encoded = false,
5515
        string $replacement = ''
5516
    ): string {
5517 92
        return ASCII::remove_invisible_characters(
5518 92
            $str,
5519 92
            $url_encoded,
5520 92
            $replacement
5521
        );
5522
    }
5523
5524
    /**
5525
     * Returns a new string with the prefix $substring removed, if present.
5526
     *
5527
     * @param string $str       <p>The input string.</p>
5528
     * @param string $substring <p>The prefix to remove.</p>
5529
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
5530
     *
5531
     * @psalm-pure
5532
     *
5533
     * @return string
5534
     *                <p>A string without the prefix $substring.</p>
5535
     */
5536
    public static function remove_left(
5537
        string $str,
5538
        string $substring,
5539
        string $encoding = 'UTF-8'
5540
    ): string {
5541
        if (
5542 12
            $substring
5543
            &&
5544 12
            \strpos($str, $substring) === 0
5545
        ) {
5546 6
            if ($encoding === 'UTF-8') {
5547 4
                return (string) \mb_substr(
5548 4
                    $str,
5549 4
                    (int) \mb_strlen($substring)
5550
                );
5551
            }
5552
5553 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
5554
5555 2
            return (string) self::substr(
5556 2
                $str,
5557 2
                (int) self::strlen($substring, $encoding),
5558 2
                null,
5559 2
                $encoding
5560
            );
5561
        }
5562
5563 6
        return $str;
5564
    }
5565
5566
    /**
5567
     * Returns a new string with the suffix $substring removed, if present.
5568
     *
5569
     * @param string $str
5570
     * @param string $substring <p>The suffix to remove.</p>
5571
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
5572
     *
5573
     * @psalm-pure
5574
     *
5575
     * @return string
5576
     *                <p>A string having a $str without the suffix $substring.</p>
5577
     */
5578
    public static function remove_right(
5579
        string $str,
5580
        string $substring,
5581
        string $encoding = 'UTF-8'
5582
    ): string {
5583 12
        if ($substring && \substr($str, -\strlen($substring)) === $substring) {
5584 6
            if ($encoding === 'UTF-8') {
5585 4
                return (string) \mb_substr(
5586 4
                    $str,
5587 4
                    0,
5588 4
                    (int) \mb_strlen($str) - (int) \mb_strlen($substring)
5589
                );
5590
            }
5591
5592 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
5593
5594 2
            return (string) self::substr(
5595 2
                $str,
5596 2
                0,
5597 2
                (int) self::strlen($str, $encoding) - (int) self::strlen($substring, $encoding),
5598 2
                $encoding
5599
            );
5600
        }
5601
5602 6
        return $str;
5603
    }
5604
5605
    /**
5606
     * Replaces all occurrences of $search in $str by $replacement.
5607
     *
5608
     * @param string $str            <p>The input string.</p>
5609
     * @param string $search         <p>The needle to search for.</p>
5610
     * @param string $replacement    <p>The string to replace with.</p>
5611
     * @param bool   $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
5612
     *
5613
     * @psalm-pure
5614
     *
5615
     * @return string
5616
     *                <p>A string with replaced parts.</p>
5617
     */
5618
    public static function replace(
5619
        string $str,
5620
        string $search,
5621
        string $replacement,
5622
        bool $case_sensitive = true
5623
    ): string {
5624 29
        if ($case_sensitive) {
5625 22
            return \str_replace($search, $replacement, $str);
5626
        }
5627
5628 7
        return self::str_ireplace($search, $replacement, $str);
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::str_ireplac...ch, $replacement, $str) could return the type string[] which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
5629
    }
5630
5631
    /**
5632
     * Replaces all occurrences of $search in $str by $replacement.
5633
     *
5634
     * @param string       $str            <p>The input string.</p>
5635
     * @param array        $search         <p>The elements to search for.</p>
5636
     * @param array|string $replacement    <p>The string to replace with.</p>
5637
     * @param bool         $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
5638
     *
5639
     * @psalm-pure
5640
     *
5641
     * @return string
5642
     *                <p>A string with replaced parts.</p>
5643
     */
5644
    public static function replace_all(
5645
        string $str,
5646
        array $search,
5647
        $replacement,
5648
        bool $case_sensitive = true
5649
    ): string {
5650 30
        if ($case_sensitive) {
5651 23
            return \str_replace($search, $replacement, $str);
5652
        }
5653
5654 7
        return self::str_ireplace($search, $replacement, $str);
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::str_ireplac...ch, $replacement, $str) could return the type string[] which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
5655
    }
5656
5657
    /**
5658
     * Replace the diamond question mark (�) and invalid-UTF8 chars with the replacement.
5659
     *
5660
     * EXAMPLE: <code>UTF8::replace_diamond_question_mark('中文空白�', ''); // '中文空白'</code>
5661
     *
5662
     * @param string $str                        <p>The input string</p>
5663
     * @param string $replacement_char           <p>The replacement character.</p>
5664
     * @param bool   $process_invalid_utf8_chars <p>Convert invalid UTF-8 chars </p>
5665
     *
5666
     * @psalm-pure
5667
     *
5668
     * @return string
5669
     *                <p>A string without diamond question marks (�).</p>
5670
     */
5671
    public static function replace_diamond_question_mark(
5672
        string $str,
5673
        string $replacement_char = '',
5674
        bool $process_invalid_utf8_chars = true
5675
    ): string {
5676 35
        if ($str === '') {
5677 9
            return '';
5678
        }
5679
5680 35
        if ($process_invalid_utf8_chars) {
5681 35
            if ($replacement_char === '') {
5682 35
                $replacement_char_helper = 'none';
5683
            } else {
5684 2
                $replacement_char_helper = \ord($replacement_char);
5685
            }
5686
5687 35
            if (self::$SUPPORT['mbstring'] === false) {
5688
                // if there is no native support for "mbstring",
5689
                // then we need to clean the string before ...
5690
                $str = self::clean($str);
5691
            }
5692
5693
            /**
5694
             * @psalm-suppress ImpureFunctionCall - we will reset the value in the next step
5695
             */
5696 35
            $save = \mb_substitute_character();
5697
            /** @noinspection PhpUsageOfSilenceOperatorInspection - ignore "Unknown character" warnings, it's working anyway */
5698 35
            @\mb_substitute_character($replacement_char_helper);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mb_substitute_character(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

5698
            /** @scrutinizer ignore-unhandled */ @\mb_substitute_character($replacement_char_helper);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
5699
            // the polyfill maybe return false, so cast to string
5700 35
            $str = (string) \mb_convert_encoding($str, 'UTF-8', 'UTF-8');
5701 35
            \mb_substitute_character($save);
5702
        }
5703
5704 35
        return \str_replace(
5705
            [
5706 35
                "\xEF\xBF\xBD",
5707
                '�',
5708
            ],
5709
            [
5710 35
                $replacement_char,
5711 35
                $replacement_char,
5712
            ],
5713 35
            $str
5714
        );
5715
    }
5716
5717
    /**
5718
     * Strip whitespace or other characters from the end of a UTF-8 string.
5719
     *
5720
     * EXAMPLE: <code>UTF8::rtrim('-ABC-中文空白-  '); // '-ABC-中文空白-'</code>
5721
     *
5722
     * @param string      $str   <p>The string to be trimmed.</p>
5723
     * @param string|null $chars <p>Optional characters to be stripped.</p>
5724
     *
5725
     * @psalm-pure
5726
     *
5727
     * @return string
5728
     *                <p>A string with unwanted characters stripped from the right.</p>
5729
     */
5730
    public static function rtrim(string $str = '', string $chars = null): string
5731
    {
5732 21
        if ($str === '') {
5733 3
            return '';
5734
        }
5735
5736 20
        if (self::$SUPPORT['mbstring'] === true) {
5737 20
            if ($chars !== null) {
5738
                /** @noinspection PregQuoteUsageInspection */
5739 9
                $chars = \preg_quote($chars);
5740 9
                $pattern = "[${chars}]+$";
5741
            } else {
5742 14
                $pattern = '[\\s]+$';
5743
            }
5744
5745
            /** @noinspection PhpComposerExtensionStubsInspection */
5746 20
            return (string) \mb_ereg_replace($pattern, '', $str);
5747
        }
5748
5749
        if ($chars !== null) {
5750
            $chars = \preg_quote($chars, '/');
5751
            $pattern = "[${chars}]+$";
5752
        } else {
5753
            $pattern = '[\\s]+$';
5754
        }
5755
5756
        return self::regex_replace($str, $pattern, '');
5757
    }
5758
5759
    /**
5760
     * WARNING: Print native UTF-8 support (libs) by default, e.g. for debugging.
5761
     *
5762
     * @param bool $useEcho
5763
     *
5764
     * @psalm-pure
5765
     *
5766
     * @return string|void
5767
     */
5768
    public static function showSupport(bool $useEcho = true)
5769
    {
5770
        // init
5771 2
        $html = '';
5772
5773 2
        $html .= '<pre>';
5774
        /** @noinspection AlterInForeachInspection */
5775 2
        foreach (self::$SUPPORT as $key => &$value) {
5776 2
            $html .= $key . ' - ' . \print_r($value, true) . "\n<br>";
5777
        }
5778 2
        $html .= '</pre>';
5779
5780 2
        if ($useEcho) {
5781 1
            echo $html;
5782
        }
5783
5784 2
        return $html;
5785
    }
5786
5787
    /**
5788
     * Converts a UTF-8 character to HTML Numbered Entity like "&#123;".
5789
     *
5790
     * EXAMPLE: <code>UTF8::single_chr_html_encode('κ'); // '&#954;'</code>
5791
     *
5792
     * @param string $char             <p>The Unicode character to be encoded as numbered entity.</p>
5793
     * @param bool   $keep_ascii_chars <p>Set to <strong>true</strong> to keep ASCII chars.</>
5794
     * @param string $encoding         [optional] <p>Set the charset for e.g. "mb_" function</p>
5795
     *
5796
     * @psalm-pure
5797
     *
5798
     * @return string
5799
     *                <p>The HTML numbered entity for the given character.</p>
5800
     */
5801
    public static function single_chr_html_encode(
5802
        string $char,
5803
        bool $keep_ascii_chars = false,
5804
        string $encoding = 'UTF-8'
5805
    ): string {
5806 2
        if ($char === '') {
5807 2
            return '';
5808
        }
5809
5810
        if (
5811 2
            $keep_ascii_chars
5812
            &&
5813 2
            ASCII::is_ascii($char)
5814
        ) {
5815 2
            return $char;
5816
        }
5817
5818 2
        return '&#' . self::ord($char, $encoding) . ';';
5819
    }
5820
5821
    /**
5822
     * @param string $str
5823
     * @param int    $tab_length
5824
     *
5825
     * @psalm-pure
5826
     *
5827
     * @return string
5828
     */
5829
    public static function spaces_to_tabs(string $str, int $tab_length = 4): string
5830
    {
5831 5
        if ($tab_length === 4) {
5832 3
            $tab = '    ';
5833 2
        } elseif ($tab_length === 2) {
5834 1
            $tab = '  ';
5835
        } else {
5836 1
            $tab = \str_repeat(' ', $tab_length);
5837
        }
5838
5839 5
        return \str_replace($tab, "\t", $str);
5840
    }
5841
5842
    /**
5843
     * alias for "UTF8::str_split()"
5844
     *
5845
     * @param int|string $str
5846
     * @param int        $length
5847
     * @param bool       $clean_utf8
5848
     *
5849
     * @psalm-pure
5850
     *
5851
     * @return string[]
5852
     *
5853
     * @see        UTF8::str_split()
5854
     * @deprecated <p>please use "UTF8::str_split()"</p>
5855
     */
5856
    public static function split(
5857
        $str,
5858
        int $length = 1,
5859
        bool $clean_utf8 = false
5860
    ): array {
5861
        /** @var string[] */
5862 9
        return self::str_split($str, $length, $clean_utf8);
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::str_split($str, $length, $clean_utf8) returns an array which contains values of type array|string[] which are incompatible with the documented value type string.
Loading history...
5863
    }
5864
5865
    /**
5866
     * alias for "UTF8::str_starts_with()"
5867
     *
5868
     * @param string $haystack
5869
     * @param string $needle
5870
     *
5871
     * @psalm-pure
5872
     *
5873
     * @return bool
5874
     *
5875
     * @see        UTF8::str_starts_with()
5876
     * @deprecated <p>please use "UTF8::str_starts_with()"</p>
5877
     */
5878
    public static function str_begins(string $haystack, string $needle): bool
5879
    {
5880 1
        return self::str_starts_with($haystack, $needle);
5881
    }
5882
5883
    /**
5884
     * Returns a camelCase version of the string. Trims surrounding spaces,
5885
     * capitalizes letters following digits, spaces, dashes and underscores,
5886
     * and removes spaces, dashes, as well as underscores.
5887
     *
5888
     * @param string      $str                           <p>The input string.</p>
5889
     * @param string      $encoding                      [optional] <p>Default: 'UTF-8'</p>
5890
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
5891
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
5892
     *                                                   tr</p>
5893
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ
5894
     *                                                   -> ß</p>
5895
     *
5896
     * @psalm-pure
5897
     *
5898
     * @return string
5899
     */
5900
    public static function str_camelize(
5901
        string $str,
5902
        string $encoding = 'UTF-8',
5903
        bool $clean_utf8 = false,
5904
        string $lang = null,
5905
        bool $try_to_keep_the_string_length = false
5906
    ): string {
5907 32
        if ($clean_utf8) {
5908
            $str = self::clean($str);
5909
        }
5910
5911 32
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
5912 26
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
5913
        }
5914
5915 32
        $str = self::lcfirst(
5916 32
            \trim($str),
5917 32
            $encoding,
5918 32
            false,
5919 32
            $lang,
5920 32
            $try_to_keep_the_string_length
5921
        );
5922 32
        $str = (string) \preg_replace('/^[-_]+/', '', $str);
5923
5924 32
        $use_mb_functions = $lang === null && !$try_to_keep_the_string_length;
5925
5926 32
        $str = (string) \preg_replace_callback(
5927 32
            '/[-_\\s]+(.)?/u',
5928
            /**
5929
             * @param array $match
5930
             *
5931
             * @psalm-pure
5932
             *
5933
             * @return string
5934
             */
5935
            static function (array $match) use ($use_mb_functions, $encoding, $lang, $try_to_keep_the_string_length): string {
5936 27
                if (isset($match[1])) {
5937 27
                    if ($use_mb_functions) {
5938 27
                        if ($encoding === 'UTF-8') {
5939 27
                            return \mb_strtoupper($match[1]);
5940
                        }
5941
5942
                        return \mb_strtoupper($match[1], $encoding);
5943
                    }
5944
5945
                    return self::strtoupper($match[1], $encoding, false, $lang, $try_to_keep_the_string_length);
5946
                }
5947
5948 1
                return '';
5949 32
            },
5950 32
            $str
5951
        );
5952
5953 32
        return (string) \preg_replace_callback(
5954 32
            '/[\\p{N}]+(.)?/u',
5955
            /**
5956
             * @param array $match
5957
             *
5958
             * @psalm-pure
5959
             *
5960
             * @return string
5961
             */
5962
            static function (array $match) use ($use_mb_functions, $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length): string {
5963 6
                if ($use_mb_functions) {
5964 6
                    if ($encoding === 'UTF-8') {
5965 6
                        return \mb_strtoupper($match[0]);
5966
                    }
5967
5968
                    return \mb_strtoupper($match[0], $encoding);
5969
                }
5970
5971
                return self::strtoupper($match[0], $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length);
5972 32
            },
5973 32
            $str
5974
        );
5975
    }
5976
5977
    /**
5978
     * Returns the string with the first letter of each word capitalized,
5979
     * except for when the word is a name which shouldn't be capitalized.
5980
     *
5981
     * @param string $str
5982
     *
5983
     * @psalm-pure
5984
     *
5985
     * @return string
5986
     *                <p>A string with $str capitalized.</p>
5987
     */
5988
    public static function str_capitalize_name(string $str): string
5989
    {
5990 1
        return self::str_capitalize_name_helper(
5991 1
            self::str_capitalize_name_helper(
5992 1
                self::collapse_whitespace($str),
5993 1
                ' '
5994
            ),
5995 1
            '-'
5996
        );
5997
    }
5998
5999
    /**
6000
     * Returns true if the string contains $needle, false otherwise. By default
6001
     * the comparison is case-sensitive, but can be made insensitive by setting
6002
     * $case_sensitive to false.
6003
     *
6004
     * @param string $haystack       <p>The input string.</p>
6005
     * @param string $needle         <p>Substring to look for.</p>
6006
     * @param bool   $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
6007
     *
6008
     * @psalm-pure
6009
     *
6010
     * @return bool
6011
     *              <p>Whether or not $haystack contains $needle.</p>
6012
     */
6013
    public static function str_contains(
6014
        string $haystack,
6015
        string $needle,
6016
        bool $case_sensitive = true
6017
    ): bool {
6018 21
        if ($case_sensitive) {
6019 11
            if (\PHP_VERSION_ID >= 80000) {
6020
                /** @phpstan-ignore-next-line - only for PHP8 */
6021
                return \str_contains($haystack, $needle);
0 ignored issues
show
Bug introduced by
The function str_contains was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6021
                return /** @scrutinizer ignore-call */ \str_contains($haystack, $needle);
Loading history...
6022
            }
6023
6024 11
            return \strpos($haystack, $needle) !== false;
6025
        }
6026
6027 10
        return \mb_stripos($haystack, $needle) !== false;
6028
    }
6029
6030
    /**
6031
     * Returns true if the string contains all $needles, false otherwise. By
6032
     * default the comparison is case-sensitive, but can be made insensitive by
6033
     * setting $case_sensitive to false.
6034
     *
6035
     * @param string $haystack       <p>The input string.</p>
6036
     * @param array  $needles        <p>SubStrings to look for.</p>
6037
     * @param bool   $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
6038
     *
6039
     * @psalm-pure
6040
     *
6041
     * @return bool
6042
     *              <p>Whether or not $haystack contains $needle.</p>
6043
     */
6044
    public static function str_contains_all(
6045
        string $haystack,
6046
        array $needles,
6047
        bool $case_sensitive = true
6048
    ): bool {
6049 45
        if ($haystack === '' || $needles === []) {
6050 1
            return false;
6051
        }
6052
6053
        /** @noinspection LoopWhichDoesNotLoopInspection */
6054 44
        foreach ($needles as &$needle) {
6055 44
            if ($case_sensitive) {
6056
                /** @noinspection NestedPositiveIfStatementsInspection */
6057 24
                if (!$needle || \strpos($haystack, $needle) === false) {
6058 12
                    return false;
6059
                }
6060
            }
6061
6062 33
            if (!$needle || \mb_stripos($haystack, $needle) === false) {
6063 33
                return false;
6064
            }
6065
        }
6066
6067 24
        return true;
6068
    }
6069
6070
    /**
6071
     * Returns true if the string contains any $needles, false otherwise. By
6072
     * default the comparison is case-sensitive, but can be made insensitive by
6073
     * setting $case_sensitive to false.
6074
     *
6075
     * @param string $haystack       <p>The input string.</p>
6076
     * @param array  $needles        <p>SubStrings to look for.</p>
6077
     * @param bool   $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
6078
     *
6079
     * @psalm-pure
6080
     *
6081
     * @return bool
6082
     *              <p>Whether or not $str contains $needle.</p>
6083
     */
6084
    public static function str_contains_any(
6085
        string $haystack,
6086
        array $needles,
6087
        bool $case_sensitive = true
6088
    ): bool {
6089 46
        if ($haystack === '' || $needles === []) {
6090 1
            return false;
6091
        }
6092
6093
        /** @noinspection LoopWhichDoesNotLoopInspection */
6094 45
        foreach ($needles as &$needle) {
6095 45
            if (!$needle) {
6096
                continue;
6097
            }
6098
6099 45
            if ($case_sensitive) {
6100 25
                if (\strpos($haystack, $needle) !== false) {
6101 14
                    return true;
6102
                }
6103
6104 13
                continue;
6105
            }
6106
6107 20
            if (\mb_stripos($haystack, $needle) !== false) {
6108 20
                return true;
6109
            }
6110
        }
6111
6112 19
        return false;
6113
    }
6114
6115
    /**
6116
     * Returns a lowercase and trimmed string separated by dashes. Dashes are
6117
     * inserted before uppercase characters (with the exception of the first
6118
     * character of the string), and in place of spaces as well as underscores.
6119
     *
6120
     * @param string $str      <p>The input string.</p>
6121
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6122
     *
6123
     * @psalm-pure
6124
     *
6125
     * @return string
6126
     */
6127
    public static function str_dasherize(string $str, string $encoding = 'UTF-8'): string
6128
    {
6129 19
        return self::str_delimit($str, '-', $encoding);
6130
    }
6131
6132
    /**
6133
     * Returns a lowercase and trimmed string separated by the given delimiter.
6134
     * Delimiters are inserted before uppercase characters (with the exception
6135
     * of the first character of the string), and in place of spaces, dashes,
6136
     * and underscores. Alpha delimiters are not converted to lowercase.
6137
     *
6138
     * @param string      $str                           <p>The input string.</p>
6139
     * @param string      $delimiter                     <p>Sequence used to separate parts of the string.</p>
6140
     * @param string      $encoding                      [optional] <p>Set the charset for e.g. "mb_" function</p>
6141
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
6142
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
6143
     *                                                   tr</p>
6144
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ ->
6145
     *                                                   ß</p>
6146
     *
6147
     * @psalm-pure
6148
     *
6149
     * @return string
6150
     */
6151
    public static function str_delimit(
6152
        string $str,
6153
        string $delimiter,
6154
        string $encoding = 'UTF-8',
6155
        bool $clean_utf8 = false,
6156
        string $lang = null,
6157
        bool $try_to_keep_the_string_length = false
6158
    ): string {
6159 49
        if (self::$SUPPORT['mbstring'] === true) {
6160
            /** @noinspection PhpComposerExtensionStubsInspection */
6161 49
            $str = (string) \mb_ereg_replace('\\B(\\p{Lu})', '-\1', \trim($str));
6162
6163 49
            $use_mb_functions = $lang === null && !$try_to_keep_the_string_length;
6164 49
            if ($use_mb_functions && $encoding === 'UTF-8') {
6165 22
                $str = \mb_strtolower($str);
6166
            } else {
6167 27
                $str = self::strtolower($str, $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length);
6168
            }
6169
6170
            /** @noinspection PhpComposerExtensionStubsInspection */
6171 49
            return (string) \mb_ereg_replace('[\\-_\\s]+', $delimiter, $str);
6172
        }
6173
6174
        $str = (string) \preg_replace('/\\B(\\p{Lu})/u', '-\1', \trim($str));
6175
6176
        $use_mb_functions = $lang === null && !$try_to_keep_the_string_length;
6177
        if ($use_mb_functions && $encoding === 'UTF-8') {
6178
            $str = \mb_strtolower($str);
6179
        } else {
6180
            $str = self::strtolower($str, $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length);
6181
        }
6182
6183
        return (string) \preg_replace('/[\\-_\\s]+/u', $delimiter, $str);
6184
    }
6185
6186
    /**
6187
     * Optimized "mb_detect_encoding()"-function -> with support for UTF-16 and UTF-32.
6188
     *
6189
     * EXAMPLE: <code>
6190
     * UTF8::str_detect_encoding('中文空白'); // 'UTF-8'
6191
     * UTF8::str_detect_encoding('Abc'); // 'ASCII'
6192
     * </code>
6193
     *
6194
     * @param string $str <p>The input string.</p>
6195
     *
6196
     * @psalm-pure
6197
     *
6198
     * @return false|string
6199
     *                      <p>
6200
     *                      The detected string-encoding e.g. UTF-8 or UTF-16BE,<br>
6201
     *                      otherwise it will return false e.g. for BINARY or not detected encoding.
6202
     *                      </p>
6203
     */
6204
    public static function str_detect_encoding($str)
6205
    {
6206
        // init
6207 31
        $str = (string) $str;
6208
6209
        //
6210
        // 1.) check binary strings (010001001...) like UTF-16 / UTF-32 / PDF / Images / ...
6211
        //
6212
6213 31
        if (self::is_binary($str, true)) {
6214 11
            $is_utf32 = self::is_utf32($str, false);
6215 11
            if ($is_utf32 === 1) {
6216
                return 'UTF-32LE';
6217
            }
6218 11
            if ($is_utf32 === 2) {
6219 1
                return 'UTF-32BE';
6220
            }
6221
6222 11
            $is_utf16 = self::is_utf16($str, false);
6223 11
            if ($is_utf16 === 1) {
6224 3
                return 'UTF-16LE';
6225
            }
6226 11
            if ($is_utf16 === 2) {
6227 2
                return 'UTF-16BE';
6228
            }
6229
6230
            // is binary but not "UTF-16" or "UTF-32"
6231 9
            return false;
6232
        }
6233
6234
        //
6235
        // 2.) simple check for ASCII chars
6236
        //
6237
6238 27
        if (ASCII::is_ascii($str)) {
6239 10
            return 'ASCII';
6240
        }
6241
6242
        //
6243
        // 3.) simple check for UTF-8 chars
6244
        //
6245
6246 27
        if (self::is_utf8_string($str)) {
6247 19
            return 'UTF-8';
6248
        }
6249
6250
        //
6251
        // 4.) check via "mb_detect_encoding()"
6252
        //
6253
        // INFO: UTF-16, UTF-32, UCS2 and UCS4, encoding detection will fail always with "mb_detect_encoding()"
6254
6255
        $encoding_detecting_order = [
6256 16
            'ISO-8859-1',
6257
            'ISO-8859-2',
6258
            'ISO-8859-3',
6259
            'ISO-8859-4',
6260
            'ISO-8859-5',
6261
            'ISO-8859-6',
6262
            'ISO-8859-7',
6263
            'ISO-8859-8',
6264
            'ISO-8859-9',
6265
            'ISO-8859-10',
6266
            'ISO-8859-13',
6267
            'ISO-8859-14',
6268
            'ISO-8859-15',
6269
            'ISO-8859-16',
6270
            'WINDOWS-1251',
6271
            'WINDOWS-1252',
6272
            'WINDOWS-1254',
6273
            'CP932',
6274
            'CP936',
6275
            'CP950',
6276
            'CP866',
6277
            'CP850',
6278
            'CP51932',
6279
            'CP50220',
6280
            'CP50221',
6281
            'CP50222',
6282
            'ISO-2022-JP',
6283
            'ISO-2022-KR',
6284
            'JIS',
6285
            'JIS-ms',
6286
            'EUC-CN',
6287
            'EUC-JP',
6288
        ];
6289
6290 16
        if (self::$SUPPORT['mbstring'] === true) {
6291
            // info: do not use the symfony polyfill here
6292 16
            $encoding = \mb_detect_encoding($str, $encoding_detecting_order, true);
6293 16
            if ($encoding) {
6294 16
                return $encoding;
6295
            }
6296
        }
6297
6298
        //
6299
        // 5.) check via "iconv()"
6300
        //
6301
6302
        if (self::$ENCODINGS === null) {
6303
            self::$ENCODINGS = self::getData('encodings');
6304
        }
6305
6306
        foreach (self::$ENCODINGS as $encoding_tmp) {
6307
            // INFO: //IGNORE but still throw notice
6308
            /** @noinspection PhpUsageOfSilenceOperatorInspection */
6309
            if ((string) @\iconv($encoding_tmp, $encoding_tmp . '//IGNORE', $str) === $str) {
6310
                return $encoding_tmp;
6311
            }
6312
        }
6313
6314
        return false;
6315
    }
6316
6317
    /**
6318
     * alias for "UTF8::str_ends_with()"
6319
     *
6320
     * @param string $haystack
6321
     * @param string $needle
6322
     *
6323
     * @psalm-pure
6324
     *
6325
     * @return bool
6326
     *
6327
     * @see        UTF8::str_ends_with()
6328
     * @deprecated <p>please use "UTF8::str_ends_with()"</p>
6329
     */
6330
    public static function str_ends(string $haystack, string $needle): bool
6331
    {
6332 1
        return self::str_ends_with($haystack, $needle);
6333
    }
6334
6335
    /**
6336
     * Check if the string ends with the given substring.
6337
     *
6338
     * EXAMPLE: <code>
6339
     * UTF8::str_ends_with('BeginMiddleΚόσμε', 'Κόσμε'); // true
6340
     * UTF8::str_ends_with('BeginMiddleΚόσμε', 'κόσμε'); // false
6341
     * </code>
6342
     *
6343
     * @param string $haystack <p>The string to search in.</p>
6344
     * @param string $needle   <p>The substring to search for.</p>
6345
     *
6346
     * @psalm-pure
6347
     *
6348
     * @return bool
6349
     */
6350
    public static function str_ends_with(string $haystack, string $needle): bool
6351
    {
6352 9
        if ($needle === '') {
6353 2
            return true;
6354
        }
6355
6356 9
        if ($haystack === '') {
6357
            return false;
6358
        }
6359
6360 9
        if (\PHP_VERSION_ID >= 80000) {
6361
            /** @phpstan-ignore-next-line - only for PHP8 */
6362
            return \str_ends_with($haystack, $needle);
0 ignored issues
show
Bug introduced by
The function str_ends_with was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6362
            return /** @scrutinizer ignore-call */ \str_ends_with($haystack, $needle);
Loading history...
6363
        }
6364
6365 9
        return \substr($haystack, -\strlen($needle)) === $needle;
6366
    }
6367
6368
    /**
6369
     * Returns true if the string ends with any of $substrings, false otherwise.
6370
     *
6371
     * - case-sensitive
6372
     *
6373
     * @param string   $str        <p>The input string.</p>
6374
     * @param string[] $substrings <p>Substrings to look for.</p>
6375
     *
6376
     * @psalm-pure
6377
     *
6378
     * @return bool
6379
     *              <p>Whether or not $str ends with $substring.</p>
6380
     */
6381
    public static function str_ends_with_any(string $str, array $substrings): bool
6382
    {
6383 7
        if ($substrings === []) {
6384
            return false;
6385
        }
6386
6387 7
        foreach ($substrings as &$substring) {
6388 7
            if (\substr($str, -\strlen($substring)) === $substring) {
6389 7
                return true;
6390
            }
6391
        }
6392
6393 6
        return false;
6394
    }
6395
6396
    /**
6397
     * Ensures that the string begins with $substring. If it doesn't, it's
6398
     * prepended.
6399
     *
6400
     * @param string $str       <p>The input string.</p>
6401
     * @param string $substring <p>The substring to add if not present.</p>
6402
     *
6403
     * @psalm-pure
6404
     *
6405
     * @return string
6406
     */
6407
    public static function str_ensure_left(string $str, string $substring): string
6408
    {
6409
        if (
6410 10
            $substring !== ''
6411
            &&
6412 10
            \strpos($str, $substring) === 0
6413
        ) {
6414 6
            return $str;
6415
        }
6416
6417 4
        return $substring . $str;
6418
    }
6419
6420
    /**
6421
     * Ensures that the string ends with $substring. If it doesn't, it's appended.
6422
     *
6423
     * @param string $str       <p>The input string.</p>
6424
     * @param string $substring <p>The substring to add if not present.</p>
6425
     *
6426
     * @psalm-pure
6427
     *
6428
     * @return string
6429
     */
6430
    public static function str_ensure_right(string $str, string $substring): string
6431
    {
6432
        if (
6433 10
            $str === ''
6434
            ||
6435 10
            $substring === ''
6436
            ||
6437 10
            \substr($str, -\strlen($substring)) !== $substring
6438
        ) {
6439 4
            $str .= $substring;
6440
        }
6441
6442 10
        return $str;
6443
    }
6444
6445
    /**
6446
     * Capitalizes the first word of the string, replaces underscores with
6447
     * spaces, and strips '_id'.
6448
     *
6449
     * @param string $str
6450
     *
6451
     * @psalm-pure
6452
     *
6453
     * @return string
6454
     */
6455
    public static function str_humanize($str): string
6456
    {
6457 3
        $str = \str_replace(
6458
            [
6459 3
                '_id',
6460
                '_',
6461
            ],
6462
            [
6463 3
                '',
6464
                ' ',
6465
            ],
6466 3
            $str
6467
        );
6468
6469 3
        return self::ucfirst(\trim($str));
6470
    }
6471
6472
    /**
6473
     * alias for "UTF8::str_istarts_with()"
6474
     *
6475
     * @param string $haystack
6476
     * @param string $needle
6477
     *
6478
     * @psalm-pure
6479
     *
6480
     * @return bool
6481
     *
6482
     * @see        UTF8::str_istarts_with()
6483
     * @deprecated <p>please use "UTF8::str_istarts_with()"</p>
6484
     */
6485
    public static function str_ibegins(string $haystack, string $needle): bool
6486
    {
6487 1
        return self::str_istarts_with($haystack, $needle);
6488
    }
6489
6490
    /**
6491
     * alias for "UTF8::str_iends_with()"
6492
     *
6493
     * @param string $haystack
6494
     * @param string $needle
6495
     *
6496
     * @psalm-pure
6497
     *
6498
     * @return bool
6499
     *
6500
     * @see        UTF8::str_iends_with()
6501
     * @deprecated <p>please use "UTF8::str_iends_with()"</p>
6502
     */
6503
    public static function str_iends(string $haystack, string $needle): bool
6504
    {
6505 1
        return self::str_iends_with($haystack, $needle);
6506
    }
6507
6508
    /**
6509
     * Check if the string ends with the given substring, case-insensitive.
6510
     *
6511
     * EXAMPLE: <code>
6512
     * UTF8::str_iends_with('BeginMiddleΚόσμε', 'Κόσμε'); // true
6513
     * UTF8::str_iends_with('BeginMiddleΚόσμε', 'κόσμε'); // true
6514
     * </code>
6515
     *
6516
     * @param string $haystack <p>The string to search in.</p>
6517
     * @param string $needle   <p>The substring to search for.</p>
6518
     *
6519
     * @psalm-pure
6520
     *
6521
     * @return bool
6522
     */
6523
    public static function str_iends_with(string $haystack, string $needle): bool
6524
    {
6525 12
        if ($needle === '') {
6526 2
            return true;
6527
        }
6528
6529 12
        if ($haystack === '') {
6530
            return false;
6531
        }
6532
6533 12
        return self::strcasecmp(\substr($haystack, -\strlen($needle)), $needle) === 0;
6534
    }
6535
6536
    /**
6537
     * Returns true if the string ends with any of $substrings, false otherwise.
6538
     *
6539
     * - case-insensitive
6540
     *
6541
     * @param string   $str        <p>The input string.</p>
6542
     * @param string[] $substrings <p>Substrings to look for.</p>
6543
     *
6544
     * @psalm-pure
6545
     *
6546
     * @return bool
6547
     *              <p>Whether or not $str ends with $substring.</p>
6548
     */
6549
    public static function str_iends_with_any(string $str, array $substrings): bool
6550
    {
6551 4
        if ($substrings === []) {
6552
            return false;
6553
        }
6554
6555 4
        foreach ($substrings as &$substring) {
6556 4
            if (self::str_iends_with($str, $substring)) {
6557 4
                return true;
6558
            }
6559
        }
6560
6561
        return false;
6562
    }
6563
6564
    /**
6565
     * Returns the index of the first occurrence of $needle in the string,
6566
     * and false if not found. Accepts an optional offset from which to begin
6567
     * the search.
6568
     *
6569
     * @param string $str      <p>The input string.</p>
6570
     * @param string $needle   <p>Substring to look for.</p>
6571
     * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
6572
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6573
     *
6574
     * @psalm-pure
6575
     *
6576
     * @return false|int
6577
     *                   <p>The occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
6578
     *
6579
     * @see        UTF8::stripos()
6580
     * @deprecated <p>please use "UTF8::stripos()"</p>
6581
     */
6582
    public static function str_iindex_first(
6583
        string $str,
6584
        string $needle,
6585
        int $offset = 0,
6586
        string $encoding = 'UTF-8'
6587
    ) {
6588 1
        return self::stripos(
6589 1
            $str,
6590 1
            $needle,
6591 1
            $offset,
6592 1
            $encoding
6593
        );
6594
    }
6595
6596
    /**
6597
     * Returns the index of the last occurrence of $needle in the string,
6598
     * and false if not found. Accepts an optional offset from which to begin
6599
     * the search. Offsets may be negative to count from the last character
6600
     * in the string.
6601
     *
6602
     * @param string $str      <p>The input string.</p>
6603
     * @param string $needle   <p>Substring to look for.</p>
6604
     * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
6605
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6606
     *
6607
     * @psalm-pure
6608
     *
6609
     * @return false|int
6610
     *                   <p>The last occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
6611
     *
6612
     * @see        UTF8::strripos()
6613
     * @deprecated <p>please use "UTF8::strripos()"</p>
6614
     */
6615
    public static function str_iindex_last(
6616
        string $str,
6617
        string $needle,
6618
        int $offset = 0,
6619
        string $encoding = 'UTF-8'
6620
    ) {
6621 10
        return self::strripos(
6622 10
            $str,
6623 10
            $needle,
6624 10
            $offset,
6625 10
            $encoding
6626
        );
6627
    }
6628
6629
    /**
6630
     * Returns the index of the first occurrence of $needle in the string,
6631
     * and false if not found. Accepts an optional offset from which to begin
6632
     * the search.
6633
     *
6634
     * @param string $str      <p>The input string.</p>
6635
     * @param string $needle   <p>Substring to look for.</p>
6636
     * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
6637
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6638
     *
6639
     * @psalm-pure
6640
     *
6641
     * @return false|int
6642
     *                   <p>The occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
6643
     *
6644
     * @see        UTF8::strpos()
6645
     * @deprecated <p>please use "UTF8::strpos()"</p>
6646
     */
6647
    public static function str_index_first(
6648
        string $str,
6649
        string $needle,
6650
        int $offset = 0,
6651
        string $encoding = 'UTF-8'
6652
    ) {
6653 11
        return self::strpos(
6654 11
            $str,
6655 11
            $needle,
6656 11
            $offset,
6657 11
            $encoding
6658
        );
6659
    }
6660
6661
    /**
6662
     * Returns the index of the last occurrence of $needle in the string,
6663
     * and false if not found. Accepts an optional offset from which to begin
6664
     * the search. Offsets may be negative to count from the last character
6665
     * in the string.
6666
     *
6667
     * @param string $str      <p>The input string.</p>
6668
     * @param string $needle   <p>Substring to look for.</p>
6669
     * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
6670
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6671
     *
6672
     * @psalm-pure
6673
     *
6674
     * @return false|int
6675
     *                   <p>The last occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
6676
     *
6677
     * @see        UTF8::strrpos()
6678
     * @deprecated <p>please use "UTF8::strrpos()"</p>
6679
     */
6680
    public static function str_index_last(
6681
        string $str,
6682
        string $needle,
6683
        int $offset = 0,
6684
        string $encoding = 'UTF-8'
6685
    ) {
6686 10
        return self::strrpos(
6687 10
            $str,
6688 10
            $needle,
6689 10
            $offset,
6690 10
            $encoding
6691
        );
6692
    }
6693
6694
    /**
6695
     * Inserts $substring into the string at the $index provided.
6696
     *
6697
     * @param string $str       <p>The input string.</p>
6698
     * @param string $substring <p>String to be inserted.</p>
6699
     * @param int    $index     <p>The index at which to insert the substring.</p>
6700
     * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
6701
     *
6702
     * @psalm-pure
6703
     *
6704
     * @return string
6705
     */
6706
    public static function str_insert(
6707
        string $str,
6708
        string $substring,
6709
        int $index,
6710
        string $encoding = 'UTF-8'
6711
    ): string {
6712 8
        if ($encoding === 'UTF-8') {
6713 4
            $len = (int) \mb_strlen($str);
6714 4
            if ($index > $len) {
6715
                return $str;
6716
            }
6717
6718
            /** @noinspection UnnecessaryCastingInspection */
6719 4
            return (string) \mb_substr($str, 0, $index) .
6720 4
                   $substring .
6721 4
                   (string) \mb_substr($str, $index, $len);
6722
        }
6723
6724 4
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
6725
6726 4
        $len = (int) self::strlen($str, $encoding);
6727 4
        if ($index > $len) {
6728 1
            return $str;
6729
        }
6730
6731 3
        return ((string) self::substr($str, 0, $index, $encoding)) .
6732 3
               $substring .
6733 3
               ((string) self::substr($str, $index, $len, $encoding));
6734
    }
6735
6736
    /**
6737
     * Case-insensitive and UTF-8 safe version of <function>str_replace</function>.
6738
     *
6739
     * EXAMPLE: <code>
6740
     * UTF8::str_ireplace('lIzÆ', 'lise', 'Iñtërnâtiônàlizætiøn'); // 'Iñtërnâtiônàlisetiøn'
6741
     * </code>
6742
     *
6743
     * @see http://php.net/manual/en/function.str-ireplace.php
6744
     *
6745
     * @param string|string[] $search      <p>
6746
     *                                     Every replacement with search array is
6747
     *                                     performed on the result of previous replacement.
6748
     *                                     </p>
6749
     * @param string|string[] $replacement <p>The replacement.</p>
6750
     * @param string|string[] $subject     <p>
6751
     *                                     If subject is an array, then the search and
6752
     *                                     replace is performed with every entry of
6753
     *                                     subject, and the return value is an array as
6754
     *                                     well.
6755
     *                                     </p>
6756
     * @param int             $count       [optional] <p>
6757
     *                                     The number of matched and replaced needles will
6758
     *                                     be returned in count which is passed by
6759
     *                                     reference.
6760
     *                                     </p>
6761
     *
6762
     * @psalm-pure
6763
     *
6764
     * @return string|string[]
6765
     *                         <p>A string or an array of replacements.</p>
6766
     *
6767
     * @template TStrIReplaceSubject
6768
     * @phpstan-param TStrIReplaceSubject $subject
6769
     * @phpstan-return TStrIReplaceSubject
6770
     */
6771
    public static function str_ireplace($search, $replacement, $subject, &$count = null)
6772
    {
6773 29
        $search = (array) $search;
6774
6775
        /** @noinspection AlterInForeachInspection */
6776 29
        foreach ($search as &$s) {
6777 29
            $s = (string) $s;
6778 29
            if ($s === '') {
6779 6
                $s = '/^(?<=.)$/';
6780
            } else {
6781 29
                $s = '/' . \preg_quote($s, '/') . '/ui';
6782
            }
6783
        }
6784
6785
        // fallback
6786
        /** @phpstan-ignore-next-line - only a fallback for PHP8 */
6787 29
        if ($replacement === null) {
0 ignored issues
show
introduced by
The condition $replacement === null is always false.
Loading history...
6788 1
            $replacement = '';
6789
        }
6790
        /** @phpstan-ignore-next-line - only a fallback for PHP8 */
6791 29
        if ($subject === null) {
6792 1
            $subject = '';
6793
        }
6794
6795
        /**
6796
         * @psalm-suppress PossiblyNullArgument
6797
         * @phpstan-var TStrIReplaceSubject $subject
6798
         */
6799 29
        $subject = \preg_replace($search, $replacement, $subject, -1, $count);
6800
6801 29
        return $subject;
6802
    }
6803
6804
    /**
6805
     * Replaces $search from the beginning of string with $replacement.
6806
     *
6807
     * @param string $str         <p>The input string.</p>
6808
     * @param string $search      <p>The string to search for.</p>
6809
     * @param string $replacement <p>The replacement.</p>
6810
     *
6811
     * @psalm-pure
6812
     *
6813
     * @return string
6814
     *                <p>The string after the replacement.</p>
6815
     */
6816
    public static function str_ireplace_beginning(string $str, string $search, string $replacement): string
6817
    {
6818 17
        if ($str === '') {
6819 4
            if ($replacement === '') {
6820 2
                return '';
6821
            }
6822
6823 2
            if ($search === '') {
6824 2
                return $replacement;
6825
            }
6826
        }
6827
6828 13
        if ($search === '') {
6829 2
            return $str . $replacement;
6830
        }
6831
6832 11
        $searchLength = \strlen($search);
6833 11
        if (\strncasecmp($str, $search, $searchLength) === 0) {
6834 10
            return $replacement . \substr($str, $searchLength);
6835
        }
6836
6837 1
        return $str;
6838
    }
6839
6840
    /**
6841
     * Replaces $search from the ending of string with $replacement.
6842
     *
6843
     * @param string $str         <p>The input string.</p>
6844
     * @param string $search      <p>The string to search for.</p>
6845
     * @param string $replacement <p>The replacement.</p>
6846
     *
6847
     * @psalm-pure
6848
     *
6849
     * @return string
6850
     *                <p>The string after the replacement.</p>
6851
     */
6852
    public static function str_ireplace_ending(string $str, string $search, string $replacement): string
6853
    {
6854 17
        if ($str === '') {
6855 4
            if ($replacement === '') {
6856 2
                return '';
6857
            }
6858
6859 2
            if ($search === '') {
6860 2
                return $replacement;
6861
            }
6862
        }
6863
6864 13
        if ($search === '') {
6865 2
            return $str . $replacement;
6866
        }
6867
6868 11
        if (\stripos($str, $search, \strlen($str) - \strlen($search)) !== false) {
6869 9
            $str = \substr($str, 0, -\strlen($search)) . $replacement;
6870
        }
6871
6872 11
        return $str;
6873
    }
6874
6875
    /**
6876
     * Check if the string starts with the given substring, case-insensitive.
6877
     *
6878
     * EXAMPLE: <code>
6879
     * UTF8::str_istarts_with('ΚόσμεMiddleEnd', 'Κόσμε'); // true
6880
     * UTF8::str_istarts_with('ΚόσμεMiddleEnd', 'κόσμε'); // true
6881
     * </code>
6882
     *
6883
     * @param string $haystack <p>The string to search in.</p>
6884
     * @param string $needle   <p>The substring to search for.</p>
6885
     *
6886
     * @psalm-pure
6887
     *
6888
     * @return bool
6889
     */
6890
    public static function str_istarts_with(string $haystack, string $needle): bool
6891
    {
6892 13
        if ($needle === '') {
6893 2
            return true;
6894
        }
6895
6896 13
        if ($haystack === '') {
6897
            return false;
6898
        }
6899
6900 13
        return self::stripos($haystack, $needle) === 0;
6901
    }
6902
6903
    /**
6904
     * Returns true if the string begins with any of $substrings, false otherwise.
6905
     *
6906
     * - case-insensitive
6907
     *
6908
     * @param string $str        <p>The input string.</p>
6909
     * @param array  $substrings <p>Substrings to look for.</p>
6910
     *
6911
     * @psalm-pure
6912
     *
6913
     * @return bool
6914
     *              <p>Whether or not $str starts with $substring.</p>
6915
     */
6916
    public static function str_istarts_with_any(string $str, array $substrings): bool
6917
    {
6918 5
        if ($str === '') {
6919
            return false;
6920
        }
6921
6922 5
        if ($substrings === []) {
6923
            return false;
6924
        }
6925
6926 5
        foreach ($substrings as &$substring) {
6927 5
            if (self::str_istarts_with($str, $substring)) {
6928 5
                return true;
6929
            }
6930
        }
6931
6932 1
        return false;
6933
    }
6934
6935
    /**
6936
     * Gets the substring after the first occurrence of a separator.
6937
     *
6938
     * @param string $str       <p>The input string.</p>
6939
     * @param string $separator <p>The string separator.</p>
6940
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
6941
     *
6942
     * @psalm-pure
6943
     *
6944
     * @return string
6945
     */
6946
    public static function str_isubstr_after_first_separator(
6947
        string $str,
6948
        string $separator,
6949
        string $encoding = 'UTF-8'
6950
    ): string {
6951 1
        if ($separator === '' || $str === '') {
6952 1
            return '';
6953
        }
6954
6955 1
        $offset = self::stripos($str, $separator);
6956 1
        if ($offset === false) {
6957 1
            return '';
6958
        }
6959
6960 1
        if ($encoding === 'UTF-8') {
6961 1
            return (string) \mb_substr(
6962 1
                $str,
6963 1
                $offset + (int) \mb_strlen($separator)
6964
            );
6965
        }
6966
6967
        return (string) self::substr(
6968
            $str,
6969
            $offset + (int) self::strlen($separator, $encoding),
6970
            null,
6971
            $encoding
6972
        );
6973
    }
6974
6975
    /**
6976
     * Gets the substring after the last occurrence of a separator.
6977
     *
6978
     * @param string $str       <p>The input string.</p>
6979
     * @param string $separator <p>The string separator.</p>
6980
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
6981
     *
6982
     * @psalm-pure
6983
     *
6984
     * @return string
6985
     */
6986
    public static function str_isubstr_after_last_separator(
6987
        string $str,
6988
        string $separator,
6989
        string $encoding = 'UTF-8'
6990
    ): string {
6991 1
        if ($separator === '' || $str === '') {
6992 1
            return '';
6993
        }
6994
6995 1
        $offset = self::strripos($str, $separator);
6996 1
        if ($offset === false) {
6997 1
            return '';
6998
        }
6999
7000 1
        if ($encoding === 'UTF-8') {
7001 1
            return (string) \mb_substr(
7002 1
                $str,
7003 1
                $offset + (int) self::strlen($separator)
7004
            );
7005
        }
7006
7007
        return (string) self::substr(
7008
            $str,
7009
            $offset + (int) self::strlen($separator, $encoding),
7010
            null,
7011
            $encoding
7012
        );
7013
    }
7014
7015
    /**
7016
     * Gets the substring before the first occurrence of a separator.
7017
     *
7018
     * @param string $str       <p>The input string.</p>
7019
     * @param string $separator <p>The string separator.</p>
7020
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
7021
     *
7022
     * @psalm-pure
7023
     *
7024
     * @return string
7025
     */
7026
    public static function str_isubstr_before_first_separator(
7027
        string $str,
7028
        string $separator,
7029
        string $encoding = 'UTF-8'
7030
    ): string {
7031 1
        if ($separator === '' || $str === '') {
7032 1
            return '';
7033
        }
7034
7035 1
        $offset = self::stripos($str, $separator);
7036 1
        if ($offset === false) {
7037 1
            return '';
7038
        }
7039
7040 1
        if ($encoding === 'UTF-8') {
7041 1
            return (string) \mb_substr($str, 0, $offset);
7042
        }
7043
7044
        return (string) self::substr($str, 0, $offset, $encoding);
7045
    }
7046
7047
    /**
7048
     * Gets the substring before the last occurrence of a separator.
7049
     *
7050
     * @param string $str       <p>The input string.</p>
7051
     * @param string $separator <p>The string separator.</p>
7052
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
7053
     *
7054
     * @psalm-pure
7055
     *
7056
     * @return string
7057
     */
7058
    public static function str_isubstr_before_last_separator(
7059
        string $str,
7060
        string $separator,
7061
        string $encoding = 'UTF-8'
7062
    ): string {
7063 1
        if ($separator === '' || $str === '') {
7064 1
            return '';
7065
        }
7066
7067 1
        if ($encoding === 'UTF-8') {
7068 1
            $offset = \mb_strripos($str, $separator);
7069 1
            if ($offset === false) {
7070 1
                return '';
7071
            }
7072
7073 1
            return (string) \mb_substr($str, 0, $offset);
7074
        }
7075
7076
        $offset = self::strripos($str, $separator, 0, $encoding);
7077
        if ($offset === false) {
7078
            return '';
7079
        }
7080
7081
        return (string) self::substr($str, 0, $offset, $encoding);
7082
    }
7083
7084
    /**
7085
     * Gets the substring after (or before via "$before_needle") the first occurrence of the "$needle".
7086
     *
7087
     * @param string $str           <p>The input string.</p>
7088
     * @param string $needle        <p>The string to look for.</p>
7089
     * @param bool   $before_needle [optional] <p>Default: false</p>
7090
     * @param string $encoding      [optional] <p>Default: 'UTF-8'</p>
7091
     *
7092
     * @psalm-pure
7093
     *
7094
     * @return string
7095
     */
7096
    public static function str_isubstr_first(
7097
        string $str,
7098
        string $needle,
7099
        bool $before_needle = false,
7100
        string $encoding = 'UTF-8'
7101
    ): string {
7102
        if (
7103 2
            $needle === ''
7104
            ||
7105 2
            $str === ''
7106
        ) {
7107 2
            return '';
7108
        }
7109
7110 2
        $part = self::stristr(
7111 2
            $str,
7112 2
            $needle,
7113 2
            $before_needle,
7114 2
            $encoding
7115
        );
7116 2
        if ($part === false) {
7117 2
            return '';
7118
        }
7119
7120 2
        return $part;
7121
    }
7122
7123
    /**
7124
     * Gets the substring after (or before via "$before_needle") the last occurrence of the "$needle".
7125
     *
7126
     * @param string $str           <p>The input string.</p>
7127
     * @param string $needle        <p>The string to look for.</p>
7128
     * @param bool   $before_needle [optional] <p>Default: false</p>
7129
     * @param string $encoding      [optional] <p>Default: 'UTF-8'</p>
7130
     *
7131
     * @psalm-pure
7132
     *
7133
     * @return string
7134
     */
7135
    public static function str_isubstr_last(
7136
        string $str,
7137
        string $needle,
7138
        bool $before_needle = false,
7139
        string $encoding = 'UTF-8'
7140
    ): string {
7141
        if (
7142 1
            $needle === ''
7143
            ||
7144 1
            $str === ''
7145
        ) {
7146 1
            return '';
7147
        }
7148
7149 1
        $part = self::strrichr(
7150 1
            $str,
7151 1
            $needle,
7152 1
            $before_needle,
7153 1
            $encoding
7154
        );
7155 1
        if ($part === false) {
7156 1
            return '';
7157
        }
7158
7159 1
        return $part;
7160
    }
7161
7162
    /**
7163
     * Returns the last $n characters of the string.
7164
     *
7165
     * @param string $str      <p>The input string.</p>
7166
     * @param int    $n        <p>Number of characters to retrieve from the end.</p>
7167
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7168
     *
7169
     * @psalm-pure
7170
     *
7171
     * @return string
7172
     */
7173
    public static function str_last_char(
7174
        string $str,
7175
        int $n = 1,
7176
        string $encoding = 'UTF-8'
7177
    ): string {
7178 12
        if ($str === '' || $n <= 0) {
7179 4
            return '';
7180
        }
7181
7182 8
        if ($encoding === 'UTF-8') {
7183 4
            return (string) \mb_substr($str, -$n);
7184
        }
7185
7186 4
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
7187
7188 4
        return (string) self::substr($str, -$n, null, $encoding);
7189
    }
7190
7191
    /**
7192
     * Limit the number of characters in a string.
7193
     *
7194
     * @param string $str        <p>The input string.</p>
7195
     * @param int    $length     [optional] <p>Default: 100</p>
7196
     * @param string $str_add_on [optional] <p>Default: …</p>
7197
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
7198
     *
7199
     * @psalm-pure
7200
     *
7201
     * @return string
7202
     */
7203
    public static function str_limit(
7204
        string $str,
7205
        int $length = 100,
7206
        string $str_add_on = '…',
7207
        string $encoding = 'UTF-8'
7208
    ): string {
7209 2
        if ($str === '' || $length <= 0) {
7210 2
            return '';
7211
        }
7212
7213 2
        if ($encoding === 'UTF-8') {
7214 2
            if ((int) \mb_strlen($str) <= $length) {
7215 2
                return $str;
7216
            }
7217
7218
            /** @noinspection UnnecessaryCastingInspection */
7219 2
            return (string) \mb_substr($str, 0, $length - (int) self::strlen($str_add_on)) . $str_add_on;
7220
        }
7221
7222
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
7223
7224
        if ((int) self::strlen($str, $encoding) <= $length) {
7225
            return $str;
7226
        }
7227
7228
        return ((string) self::substr($str, 0, $length - (int) self::strlen($str_add_on), $encoding)) . $str_add_on;
7229
    }
7230
7231
    /**
7232
     * Limit the number of characters in a string, but also after the next word.
7233
     *
7234
     * EXAMPLE: <code>UTF8::str_limit_after_word('fòô bàř fòô', 8, ''); // 'fòô bàř'</code>
7235
     *
7236
     * @param string $str        <p>The input string.</p>
7237
     * @param int    $length     [optional] <p>Default: 100</p>
7238
     * @param string $str_add_on [optional] <p>Default: …</p>
7239
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
7240
     *
7241
     * @psalm-pure
7242
     *
7243
     * @return string
7244
     */
7245
    public static function str_limit_after_word(
7246
        string $str,
7247
        int $length = 100,
7248
        string $str_add_on = '…',
7249
        string $encoding = 'UTF-8'
7250
    ): string {
7251 6
        if ($str === '' || $length <= 0) {
7252 2
            return '';
7253
        }
7254
7255 6
        if ($encoding === 'UTF-8') {
7256
            /** @noinspection UnnecessaryCastingInspection */
7257 2
            if ((int) \mb_strlen($str) <= $length) {
7258 2
                return $str;
7259
            }
7260
7261 2
            if (\mb_substr($str, $length - 1, 1) === ' ') {
7262 2
                return ((string) \mb_substr($str, 0, $length - 1)) . $str_add_on;
7263
            }
7264
7265 2
            $str = \mb_substr($str, 0, $length);
7266
7267 2
            $array = \explode(' ', $str, -1);
7268 2
            $new_str = \implode(' ', $array);
7269
7270 2
            if ($new_str === '') {
7271 2
                return ((string) \mb_substr($str, 0, $length - 1)) . $str_add_on;
7272
            }
7273
        } else {
7274 4
            if ((int) self::strlen($str, $encoding) <= $length) {
7275
                return $str;
7276
            }
7277
7278 4
            if (self::substr($str, $length - 1, 1, $encoding) === ' ') {
7279 3
                return ((string) self::substr($str, 0, $length - 1, $encoding)) . $str_add_on;
7280
            }
7281
7282
            /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
7283 1
            $str = self::substr($str, 0, $length, $encoding);
7284
            /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
7285 1
            if ($str === false) {
7286
                return '' . $str_add_on;
7287
            }
7288
7289 1
            $array = \explode(' ', $str, -1);
7290 1
            $new_str = \implode(' ', $array);
7291
7292 1
            if ($new_str === '') {
7293
                return ((string) self::substr($str, 0, $length - 1, $encoding)) . $str_add_on;
7294
            }
7295
        }
7296
7297 3
        return $new_str . $str_add_on;
7298
    }
7299
7300
    /**
7301
     * Returns the longest common prefix between the $str1 and $str2.
7302
     *
7303
     * @param string $str1     <p>The input sting.</p>
7304
     * @param string $str2     <p>Second string for comparison.</p>
7305
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7306
     *
7307
     * @psalm-pure
7308
     *
7309
     * @return string
7310
     */
7311
    public static function str_longest_common_prefix(
7312
        string $str1,
7313
        string $str2,
7314
        string $encoding = 'UTF-8'
7315
    ): string {
7316
        // init
7317 10
        $longest_common_prefix = '';
7318
7319 10
        if ($encoding === 'UTF-8') {
7320 5
            $max_length = (int) \min(
7321 5
                \mb_strlen($str1),
7322 5
                \mb_strlen($str2)
7323
            );
7324
7325 5
            for ($i = 0; $i < $max_length; ++$i) {
7326 4
                $char = \mb_substr($str1, $i, 1);
7327
7328
                if (
7329 4
                    $char !== false
7330
                    &&
7331 4
                    $char === \mb_substr($str2, $i, 1)
7332
                ) {
7333 3
                    $longest_common_prefix .= $char;
7334
                } else {
7335 3
                    break;
7336
                }
7337
            }
7338
        } else {
7339 5
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
7340
7341 5
            $max_length = (int) \min(
7342 5
                self::strlen($str1, $encoding),
7343 5
                self::strlen($str2, $encoding)
7344
            );
7345
7346 5
            for ($i = 0; $i < $max_length; ++$i) {
7347 4
                $char = self::substr($str1, $i, 1, $encoding);
7348
7349
                if (
7350 4
                    $char !== false
7351
                    &&
7352 4
                    $char === self::substr($str2, $i, 1, $encoding)
7353
                ) {
7354 3
                    $longest_common_prefix .= $char;
7355
                } else {
7356 3
                    break;
7357
                }
7358
            }
7359
        }
7360
7361 10
        return $longest_common_prefix;
7362
    }
7363
7364
    /**
7365
     * Returns the longest common substring between the $str1 and $str2.
7366
     * In the case of ties, it returns that which occurs first.
7367
     *
7368
     * @param string $str1
7369
     * @param string $str2     <p>Second string for comparison.</p>
7370
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7371
     *
7372
     * @psalm-pure
7373
     *
7374
     * @return string
7375
     *                <p>A string with its $str being the longest common substring.</p>
7376
     */
7377
    public static function str_longest_common_substring(
7378
        string $str1,
7379
        string $str2,
7380
        string $encoding = 'UTF-8'
7381
    ): string {
7382 11
        if ($str1 === '' || $str2 === '') {
7383 2
            return '';
7384
        }
7385
7386
        // Uses dynamic programming to solve
7387
        // http://en.wikipedia.org/wiki/Longest_common_substring_problem
7388
7389 9
        if ($encoding === 'UTF-8') {
7390 4
            $str_length = (int) \mb_strlen($str1);
7391 4
            $other_length = (int) \mb_strlen($str2);
7392
        } else {
7393 5
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
7394
7395 5
            $str_length = (int) self::strlen($str1, $encoding);
7396 5
            $other_length = (int) self::strlen($str2, $encoding);
7397
        }
7398
7399
        // Return if either string is empty
7400 9
        if ($str_length === 0 || $other_length === 0) {
7401
            return '';
7402
        }
7403
7404 9
        $len = 0;
7405 9
        $end = 0;
7406 9
        $table = \array_fill(
7407 9
            0,
7408 9
            $str_length + 1,
7409 9
            \array_fill(0, $other_length + 1, 0)
7410
        );
7411
7412 9
        if ($encoding === 'UTF-8') {
7413 9
            for ($i = 1; $i <= $str_length; ++$i) {
7414 9
                for ($j = 1; $j <= $other_length; ++$j) {
7415 9
                    $str_char = \mb_substr($str1, $i - 1, 1);
7416 9
                    $other_char = \mb_substr($str2, $j - 1, 1);
7417
7418 9
                    if ($str_char === $other_char) {
7419 8
                        $table[$i][$j] = $table[$i - 1][$j - 1] + 1;
7420 8
                        if ($table[$i][$j] > $len) {
7421 8
                            $len = $table[$i][$j];
7422 8
                            $end = $i;
7423
                        }
7424
                    } else {
7425 9
                        $table[$i][$j] = 0;
7426
                    }
7427
                }
7428
            }
7429
        } else {
7430
            for ($i = 1; $i <= $str_length; ++$i) {
7431
                for ($j = 1; $j <= $other_length; ++$j) {
7432
                    $str_char = self::substr($str1, $i - 1, 1, $encoding);
7433
                    $other_char = self::substr($str2, $j - 1, 1, $encoding);
7434
7435
                    if ($str_char === $other_char) {
7436
                        $table[$i][$j] = $table[$i - 1][$j - 1] + 1;
7437
                        if ($table[$i][$j] > $len) {
7438
                            $len = $table[$i][$j];
7439
                            $end = $i;
7440
                        }
7441
                    } else {
7442
                        $table[$i][$j] = 0;
7443
                    }
7444
                }
7445
            }
7446
        }
7447
7448 9
        if ($encoding === 'UTF-8') {
7449 9
            return (string) \mb_substr($str1, $end - $len, $len);
7450
        }
7451
7452
        return (string) self::substr($str1, $end - $len, $len, $encoding);
7453
    }
7454
7455
    /**
7456
     * Returns the longest common suffix between the $str1 and $str2.
7457
     *
7458
     * @param string $str1
7459
     * @param string $str2     <p>Second string for comparison.</p>
7460
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7461
     *
7462
     * @psalm-pure
7463
     *
7464
     * @return string
7465
     */
7466
    public static function str_longest_common_suffix(
7467
        string $str1,
7468
        string $str2,
7469
        string $encoding = 'UTF-8'
7470
    ): string {
7471 10
        if ($str1 === '' || $str2 === '') {
7472 2
            return '';
7473
        }
7474
7475 8
        if ($encoding === 'UTF-8') {
7476 4
            $max_length = (int) \min(
7477 4
                \mb_strlen($str1, $encoding),
7478 4
                \mb_strlen($str2, $encoding)
7479
            );
7480
7481 4
            $longest_common_suffix = '';
7482 4
            for ($i = 1; $i <= $max_length; ++$i) {
7483 4
                $char = \mb_substr($str1, -$i, 1);
7484
7485
                if (
7486 4
                    $char !== false
7487
                    &&
7488 4
                    $char === \mb_substr($str2, -$i, 1)
7489
                ) {
7490 3
                    $longest_common_suffix = $char . $longest_common_suffix;
7491
                } else {
7492 3
                    break;
7493
                }
7494
            }
7495
        } else {
7496 4
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
7497
7498 4
            $max_length = (int) \min(
7499 4
                self::strlen($str1, $encoding),
7500 4
                self::strlen($str2, $encoding)
7501
            );
7502
7503 4
            $longest_common_suffix = '';
7504 4
            for ($i = 1; $i <= $max_length; ++$i) {
7505 4
                $char = self::substr($str1, -$i, 1, $encoding);
7506
7507
                if (
7508 4
                    $char !== false
7509
                    &&
7510 4
                    $char === self::substr($str2, -$i, 1, $encoding)
7511
                ) {
7512 3
                    $longest_common_suffix = $char . $longest_common_suffix;
7513
                } else {
7514 3
                    break;
7515
                }
7516
            }
7517
        }
7518
7519 8
        return $longest_common_suffix;
7520
    }
7521
7522
    /**
7523
     * Returns true if $str matches the supplied pattern, false otherwise.
7524
     *
7525
     * @param string $str     <p>The input string.</p>
7526
     * @param string $pattern <p>Regex pattern to match against.</p>
7527
     *
7528
     * @psalm-pure
7529
     *
7530
     * @return bool
7531
     *              <p>Whether or not $str matches the pattern.</p>
7532
     */
7533
    public static function str_matches_pattern(string $str, string $pattern): bool
7534
    {
7535 10
        return (bool) \preg_match('/' . $pattern . '/u', $str);
7536
    }
7537
7538
    /**
7539
     * Returns whether or not a character exists at an index. Offsets may be
7540
     * negative to count from the last character in the string. Implements
7541
     * part of the ArrayAccess interface.
7542
     *
7543
     * @param string $str      <p>The input string.</p>
7544
     * @param int    $offset   <p>The index to check.</p>
7545
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7546
     *
7547
     * @psalm-pure
7548
     *
7549
     * @return bool
7550
     *              <p>Whether or not the index exists.</p>
7551
     */
7552
    public static function str_offset_exists(string $str, int $offset, string $encoding = 'UTF-8'): bool
7553
    {
7554
        // init
7555 6
        $length = (int) self::strlen($str, $encoding);
7556
7557 6
        if ($offset >= 0) {
7558 3
            return $length > $offset;
7559
        }
7560
7561 3
        return $length >= \abs($offset);
7562
    }
7563
7564
    /**
7565
     * Returns the character at the given index. Offsets may be negative to
7566
     * count from the last character in the string. Implements part of the
7567
     * ArrayAccess interface, and throws an OutOfBoundsException if the index
7568
     * does not exist.
7569
     *
7570
     * @param string $str      <p>The input string.</p>
7571
     * @param int    $index    <p>The <strong>index</strong> from which to retrieve the char.</p>
7572
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7573
     *
7574
     * @throws \OutOfBoundsException if the positive or negative offset does not exist
7575
     *
7576
     * @return string
7577
     *                <p>The character at the specified index.</p>
7578
     *
7579
     * @psalm-pure
7580
     */
7581
    public static function str_offset_get(string $str, int $index, string $encoding = 'UTF-8'): string
7582
    {
7583
        // init
7584 2
        $length = (int) self::strlen($str);
7585
7586
        if (
7587 2
            ($index >= 0 && $length <= $index)
7588
            ||
7589 2
            $length < \abs($index)
7590
        ) {
7591 1
            throw new \OutOfBoundsException('No character exists at the index');
7592
        }
7593
7594 1
        return self::char_at($str, $index, $encoding);
7595
    }
7596
7597
    /**
7598
     * Pad a UTF-8 string to a given length with another string.
7599
     *
7600
     * EXAMPLE: <code>UTF8::str_pad('中文空白', 10, '_', STR_PAD_BOTH); // '___中文空白___'</code>
7601
     *
7602
     * @param string     $str        <p>The input string.</p>
7603
     * @param int        $pad_length <p>The length of return string.</p>
7604
     * @param string     $pad_string [optional] <p>String to use for padding the input string.</p>
7605
     * @param int|string $pad_type   [optional] <p>
7606
     *                               Can be <strong>STR_PAD_RIGHT</strong> (default), [or string "right"]<br>
7607
     *                               <strong>STR_PAD_LEFT</strong> [or string "left"] or<br>
7608
     *                               <strong>STR_PAD_BOTH</strong> [or string "both"]
7609
     *                               </p>
7610
     * @param string     $encoding   [optional] <p>Default: 'UTF-8'</p>
7611
     *
7612
     * @psalm-pure
7613
     *
7614
     * @return string
7615
     *                <p>Returns the padded string.</p>
7616
     */
7617
    public static function str_pad(
7618
        string $str,
7619
        int $pad_length,
7620
        string $pad_string = ' ',
7621
        $pad_type = \STR_PAD_RIGHT,
7622
        string $encoding = 'UTF-8'
7623
    ): string {
7624 41
        if ($pad_length === 0 || $pad_string === '') {
7625 1
            return $str;
7626
        }
7627
7628 41
        if ($pad_type !== (int) $pad_type) {
7629 13
            if ($pad_type === 'left') {
7630 3
                $pad_type = \STR_PAD_LEFT;
7631 10
            } elseif ($pad_type === 'right') {
7632 6
                $pad_type = \STR_PAD_RIGHT;
7633 4
            } elseif ($pad_type === 'both') {
7634 3
                $pad_type = \STR_PAD_BOTH;
7635
            } else {
7636 1
                throw new \InvalidArgumentException(
7637 1
                    'Pad expects $pad_type to be "STR_PAD_*" or ' . "to be one of 'left', 'right' or 'both'"
7638
                );
7639
            }
7640
        }
7641
7642 40
        if ($encoding === 'UTF-8') {
7643 25
            $str_length = (int) \mb_strlen($str);
7644
7645 25
            if ($pad_length >= $str_length) {
7646
                switch ($pad_type) {
7647 25
                    case \STR_PAD_LEFT:
7648 8
                        $ps_length = (int) \mb_strlen($pad_string);
7649
7650 8
                        $diff = ($pad_length - $str_length);
7651
7652 8
                        $pre = (string) \mb_substr(
7653 8
                            \str_repeat($pad_string, (int) \ceil($diff / $ps_length)),
7654 8
                            0,
7655 8
                            $diff
7656
                        );
7657 8
                        $post = '';
7658
7659 8
                        break;
7660
7661 20
                    case \STR_PAD_BOTH:
7662 14
                        $diff = ($pad_length - $str_length);
7663
7664 14
                        $ps_length_left = (int) \floor($diff / 2);
7665
7666 14
                        $ps_length_right = (int) \ceil($diff / 2);
7667
7668 14
                        $pre = (string) \mb_substr(
7669 14
                            \str_repeat($pad_string, $ps_length_left),
7670 14
                            0,
7671 14
                            $ps_length_left
7672
                        );
7673 14
                        $post = (string) \mb_substr(
7674 14
                            \str_repeat($pad_string, $ps_length_right),
7675 14
                            0,
7676 14
                            $ps_length_right
7677
                        );
7678
7679 14
                        break;
7680
7681 9
                    case \STR_PAD_RIGHT:
7682
                    default:
7683 9
                        $ps_length = (int) \mb_strlen($pad_string);
7684
7685 9
                        $diff = ($pad_length - $str_length);
7686
7687 9
                        $post = (string) \mb_substr(
7688 9
                            \str_repeat($pad_string, (int) \ceil($diff / $ps_length)),
7689 9
                            0,
7690 9
                            $diff
7691
                        );
7692 9
                        $pre = '';
7693
                }
7694
7695 25
                return $pre . $str . $post;
7696
            }
7697
7698 3
            return $str;
7699
        }
7700
7701 15
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
7702
7703 15
        $str_length = (int) self::strlen($str, $encoding);
7704
7705 15
        if ($pad_length >= $str_length) {
7706
            switch ($pad_type) {
7707 14
                case \STR_PAD_LEFT:
7708 5
                    $ps_length = (int) self::strlen($pad_string, $encoding);
7709
7710 5
                    $diff = ($pad_length - $str_length);
7711
7712 5
                    $pre = (string) self::substr(
7713 5
                        \str_repeat($pad_string, (int) \ceil($diff / $ps_length)),
7714 5
                        0,
7715 5
                        $diff,
7716 5
                        $encoding
7717
                    );
7718 5
                    $post = '';
7719
7720 5
                    break;
7721
7722 9
                case \STR_PAD_BOTH:
7723 3
                    $diff = ($pad_length - $str_length);
7724
7725 3
                    $ps_length_left = (int) \floor($diff / 2);
7726
7727 3
                    $ps_length_right = (int) \ceil($diff / 2);
7728
7729 3
                    $pre = (string) self::substr(
7730 3
                        \str_repeat($pad_string, $ps_length_left),
7731 3
                        0,
7732 3
                        $ps_length_left,
7733 3
                        $encoding
7734
                    );
7735 3
                    $post = (string) self::substr(
7736 3
                        \str_repeat($pad_string, $ps_length_right),
7737 3
                        0,
7738 3
                        $ps_length_right,
7739 3
                        $encoding
7740
                    );
7741
7742 3
                    break;
7743
7744 6
                case \STR_PAD_RIGHT:
7745
                default:
7746 6
                    $ps_length = (int) self::strlen($pad_string, $encoding);
7747
7748 6
                    $diff = ($pad_length - $str_length);
7749
7750 6
                    $post = (string) self::substr(
7751 6
                        \str_repeat($pad_string, (int) \ceil($diff / $ps_length)),
7752 6
                        0,
7753 6
                        $diff,
7754 6
                        $encoding
7755
                    );
7756 6
                    $pre = '';
7757
            }
7758
7759 14
            return $pre . $str . $post;
7760
        }
7761
7762 1
        return $str;
7763
    }
7764
7765
    /**
7766
     * Returns a new string of a given length such that both sides of the
7767
     * string are padded. Alias for "UTF8::str_pad()" with a $pad_type of 'both'.
7768
     *
7769
     * @param string $str
7770
     * @param int    $length   <p>Desired string length after padding.</p>
7771
     * @param string $pad_str  [optional] <p>String used to pad, defaults to space. Default: ' '</p>
7772
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7773
     *
7774
     * @psalm-pure
7775
     *
7776
     * @return string
7777
     *                <p>The string with padding applied.</p>
7778
     */
7779
    public static function str_pad_both(
7780
        string $str,
7781
        int $length,
7782
        string $pad_str = ' ',
7783
        string $encoding = 'UTF-8'
7784
    ): string {
7785 11
        return self::str_pad(
7786 11
            $str,
7787 11
            $length,
7788 11
            $pad_str,
7789 11
            \STR_PAD_BOTH,
7790 11
            $encoding
7791
        );
7792
    }
7793
7794
    /**
7795
     * Returns a new string of a given length such that the beginning of the
7796
     * string is padded. Alias for "UTF8::str_pad()" with a $pad_type of 'left'.
7797
     *
7798
     * @param string $str
7799
     * @param int    $length   <p>Desired string length after padding.</p>
7800
     * @param string $pad_str  [optional] <p>String used to pad, defaults to space. Default: ' '</p>
7801
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7802
     *
7803
     * @psalm-pure
7804
     *
7805
     * @return string
7806
     *                <p>The string with left padding.</p>
7807
     */
7808
    public static function str_pad_left(
7809
        string $str,
7810
        int $length,
7811
        string $pad_str = ' ',
7812
        string $encoding = 'UTF-8'
7813
    ): string {
7814 7
        return self::str_pad(
7815 7
            $str,
7816 7
            $length,
7817 7
            $pad_str,
7818 7
            \STR_PAD_LEFT,
7819 7
            $encoding
7820
        );
7821
    }
7822
7823
    /**
7824
     * Returns a new string of a given length such that the end of the string
7825
     * is padded. Alias for "UTF8::str_pad()" with a $pad_type of 'right'.
7826
     *
7827
     * @param string $str
7828
     * @param int    $length   <p>Desired string length after padding.</p>
7829
     * @param string $pad_str  [optional] <p>String used to pad, defaults to space. Default: ' '</p>
7830
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7831
     *
7832
     * @psalm-pure
7833
     *
7834
     * @return string
7835
     *                <p>The string with right padding.</p>
7836
     */
7837
    public static function str_pad_right(
7838
        string $str,
7839
        int $length,
7840
        string $pad_str = ' ',
7841
        string $encoding = 'UTF-8'
7842
    ): string {
7843 7
        return self::str_pad(
7844 7
            $str,
7845 7
            $length,
7846 7
            $pad_str,
7847 7
            \STR_PAD_RIGHT,
7848 7
            $encoding
7849
        );
7850
    }
7851
7852
    /**
7853
     * Repeat a string.
7854
     *
7855
     * EXAMPLE: <code>UTF8::str_repeat("°~\xf0\x90\x28\xbc", 2); // '°~ð(¼°~ð(¼'</code>
7856
     *
7857
     * @param string $str        <p>
7858
     *                           The string to be repeated.
7859
     *                           </p>
7860
     * @param int    $multiplier <p>
7861
     *                           Number of time the input string should be
7862
     *                           repeated.
7863
     *                           </p>
7864
     *                           <p>
7865
     *                           multiplier has to be greater than or equal to 0.
7866
     *                           If the multiplier is set to 0, the function
7867
     *                           will return an empty string.
7868
     *                           </p>
7869
     *
7870
     * @psalm-pure
7871
     *
7872
     * @return string
7873
     *                <p>The repeated string.</p>
7874
     */
7875
    public static function str_repeat(string $str, int $multiplier): string
7876
    {
7877 9
        $str = self::filter($str);
7878
7879 9
        return \str_repeat($str, $multiplier);
7880
    }
7881
7882
    /**
7883
     * INFO: This is only a wrapper for "str_replace()"  -> the original functions is already UTF-8 safe.
7884
     *
7885
     * Replace all occurrences of the search string with the replacement string
7886
     *
7887
     * @see http://php.net/manual/en/function.str-replace.php
7888
     *
7889
     * @param string|string[] $search  <p>
7890
     *                                 The value being searched for, otherwise known as the needle.
7891
     *                                 An array may be used to designate multiple needles.
7892
     *                                 </p>
7893
     * @param string|string[] $replace <p>
7894
     *                                 The replacement value that replaces found search
7895
     *                                 values. An array may be used to designate multiple replacements.
7896
     *                                 </p>
7897
     * @param string|string[] $subject <p>
7898
     *                                 The string or array of strings being searched and replaced on,
7899
     *                                 otherwise known as the haystack.
7900
     *                                 </p>
7901
     *                                 <p>
7902
     *                                 If subject is an array, then the search and
7903
     *                                 replace is performed with every entry of
7904
     *                                 subject, and the return value is an array as
7905
     *                                 well.
7906
     *                                 </p>
7907
     * @param int|null        $count   [optional] <p>
7908
     *                                 If passed, this will hold the number of matched and replaced needles.
7909
     *                                 </p>
7910
     *
7911
     * @psalm-pure
7912
     *
7913
     * @return string|string[]
7914
     *                         <p>This function returns a string or an array with the replaced values.</p>
7915
     *
7916
     * @template TStrReplaceSubject
7917
     * @phpstan-param TStrReplaceSubject $subject
7918
     * @phpstan-return TStrReplaceSubject
7919
     *
7920
     * @deprecated please use \str_replace() instead
7921
     */
7922
    public static function str_replace(
7923
        $search,
7924
        $replace,
7925
        $subject,
7926
        int &$count = null
7927
    ) {
7928
        /**
7929
         * @psalm-suppress PossiblyNullArgument
7930
         * @phpstan-var TStrReplaceSubject $return;
7931
         */
7932 12
        $return = \str_replace(
7933 12
            $search,
7934 12
            $replace,
7935 12
            $subject,
7936 12
            $count
7937
        );
7938
7939 12
        return $return;
7940
    }
7941
7942
    /**
7943
     * Replaces $search from the beginning of string with $replacement.
7944
     *
7945
     * @param string $str         <p>The input string.</p>
7946
     * @param string $search      <p>The string to search for.</p>
7947
     * @param string $replacement <p>The replacement.</p>
7948
     *
7949
     * @psalm-pure
7950
     *
7951
     * @return string
7952
     *                <p>A string after the replacements.</p>
7953
     */
7954
    public static function str_replace_beginning(
7955
        string $str,
7956
        string $search,
7957
        string $replacement
7958
    ): string {
7959 17
        if ($str === '') {
7960 4
            if ($replacement === '') {
7961 2
                return '';
7962
            }
7963
7964 2
            if ($search === '') {
7965 2
                return $replacement;
7966
            }
7967
        }
7968
7969 13
        if ($search === '') {
7970 2
            return $str . $replacement;
7971
        }
7972
7973 11
        $searchLength = \strlen($search);
7974 11
        if (\strncmp($str, $search, $searchLength) === 0) {
7975 9
            return $replacement . \substr($str, $searchLength);
7976
        }
7977
7978 2
        return $str;
7979
    }
7980
7981
    /**
7982
     * Replaces $search from the ending of string with $replacement.
7983
     *
7984
     * @param string $str         <p>The input string.</p>
7985
     * @param string $search      <p>The string to search for.</p>
7986
     * @param string $replacement <p>The replacement.</p>
7987
     *
7988
     * @psalm-pure
7989
     *
7990
     * @return string
7991
     *                <p>A string after the replacements.</p>
7992
     */
7993
    public static function str_replace_ending(
7994
        string $str,
7995
        string $search,
7996
        string $replacement
7997
    ): string {
7998 17
        if ($str === '') {
7999 4
            if ($replacement === '') {
8000 2
                return '';
8001
            }
8002
8003 2
            if ($search === '') {
8004 2
                return $replacement;
8005
            }
8006
        }
8007
8008 13
        if ($search === '') {
8009 2
            return $str . $replacement;
8010
        }
8011
8012 11
        if (\strpos($str, $search, \strlen($str) - \strlen($search)) !== false) {
8013 8
            $str = \substr($str, 0, -\strlen($search)) . $replacement;
8014
        }
8015
8016 11
        return $str;
8017
    }
8018
8019
    /**
8020
     * Replace the first "$search"-term with the "$replace"-term.
8021
     *
8022
     * @param string $search
8023
     * @param string $replace
8024
     * @param string $subject
8025
     *
8026
     * @psalm-pure
8027
     *
8028
     * @return string
8029
     *
8030
     * @psalm-suppress InvalidReturnType
8031
     */
8032
    public static function str_replace_first(
8033
        string $search,
8034
        string $replace,
8035
        string $subject
8036
    ): string {
8037 2
        $pos = self::strpos($subject, $search);
8038
8039 2
        if ($pos !== false) {
8040
            /**
8041
             * @psalm-suppress InvalidReturnStatement
8042
             */
8043 2
            return self::substr_replace(
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::substr_repl...)self::strlen($search)) could return the type string[] which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
8044 2
                $subject,
8045 2
                $replace,
8046 2
                $pos,
8047 2
                (int) self::strlen($search)
8048
            );
8049
        }
8050
8051 2
        return $subject;
8052
    }
8053
8054
    /**
8055
     * Replace the last "$search"-term with the "$replace"-term.
8056
     *
8057
     * @param string $search
8058
     * @param string $replace
8059
     * @param string $subject
8060
     *
8061
     * @psalm-pure
8062
     *
8063
     * @return string
8064
     *
8065
     * @psalm-suppress InvalidReturnType
8066
     */
8067
    public static function str_replace_last(
8068
        string $search,
8069
        string $replace,
8070
        string $subject
8071
    ): string {
8072 2
        $pos = self::strrpos($subject, $search);
8073 2
        if ($pos !== false) {
8074
            /**
8075
             * @psalm-suppress InvalidReturnStatement
8076
             */
8077 2
            return self::substr_replace(
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::substr_repl...)self::strlen($search)) could return the type string[] which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
8078 2
                $subject,
8079 2
                $replace,
8080 2
                $pos,
8081 2
                (int) self::strlen($search)
8082
            );
8083
        }
8084
8085 2
        return $subject;
8086
    }
8087
8088
    /**
8089
     * Shuffles all the characters in the string.
8090
     *
8091
     * INFO: uses random algorithm which is weak for cryptography purposes
8092
     *
8093
     * EXAMPLE: <code>UTF8::str_shuffle('fòô bàř fòô'); // 'àòôřb ffòô '</code>
8094
     *
8095
     * @param string $str      <p>The input string</p>
8096
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
8097
     *
8098
     * @return string
8099
     *                <p>The shuffled string.</p>
8100
     */
8101
    public static function str_shuffle(string $str, string $encoding = 'UTF-8'): string
8102
    {
8103 5
        if ($encoding === 'UTF-8') {
8104 5
            $indexes = \range(0, (int) \mb_strlen($str) - 1);
8105
            /** @noinspection NonSecureShuffleUsageInspection */
8106 5
            \shuffle($indexes);
8107
8108
            // init
8109 5
            $shuffled_str = '';
8110
8111 5
            foreach ($indexes as &$i) {
8112 5
                $tmp_sub_str = \mb_substr($str, $i, 1);
8113 5
                if ($tmp_sub_str !== false) {
8114 5
                    $shuffled_str .= $tmp_sub_str;
8115
                }
8116
            }
8117
        } else {
8118
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
8119
8120
            $indexes = \range(0, (int) self::strlen($str, $encoding) - 1);
8121
            /** @noinspection NonSecureShuffleUsageInspection */
8122
            \shuffle($indexes);
8123
8124
            // init
8125
            $shuffled_str = '';
8126
8127
            foreach ($indexes as &$i) {
8128
                $tmp_sub_str = self::substr($str, $i, 1, $encoding);
8129
                if ($tmp_sub_str !== false) {
8130
                    $shuffled_str .= $tmp_sub_str;
8131
                }
8132
            }
8133
        }
8134
8135 5
        return $shuffled_str;
8136
    }
8137
8138
    /**
8139
     * Returns the substring beginning at $start, and up to, but not including
8140
     * the index specified by $end. If $end is omitted, the function extracts
8141
     * the remaining string. If $end is negative, it is computed from the end
8142
     * of the string.
8143
     *
8144
     * @param string   $str
8145
     * @param int      $start    <p>Initial index from which to begin extraction.</p>
8146
     * @param int|null $end      [optional] <p>Index at which to end extraction. Default: null</p>
8147
     * @param string   $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
8148
     *
8149
     * @psalm-pure
8150
     *
8151
     * @return false|string
8152
     *                      <p>The extracted substring.</p><p>If <i>str</i> is shorter than <i>start</i>
8153
     *                      characters long, <b>FALSE</b> will be returned.
8154
     */
8155
    public static function str_slice(
8156
        string $str,
8157
        int $start,
8158
        int $end = null,
8159
        string $encoding = 'UTF-8'
8160
    ) {
8161 18
        if ($encoding === 'UTF-8') {
8162 7
            if ($end === null) {
8163 1
                $length = (int) \mb_strlen($str);
8164 6
            } elseif ($end >= 0 && $end <= $start) {
8165 2
                return '';
8166 4
            } elseif ($end < 0) {
8167 1
                $length = (int) \mb_strlen($str) + $end - $start;
8168
            } else {
8169 3
                $length = $end - $start;
8170
            }
8171
8172 5
            return \mb_substr($str, $start, $length);
8173
        }
8174
8175 11
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
8176
8177 11
        if ($end === null) {
8178 5
            $length = (int) self::strlen($str, $encoding);
8179 6
        } elseif ($end >= 0 && $end <= $start) {
8180 2
            return '';
8181 4
        } elseif ($end < 0) {
8182 1
            $length = (int) self::strlen($str, $encoding) + $end - $start;
8183
        } else {
8184 3
            $length = $end - $start;
8185
        }
8186
8187 9
        return self::substr($str, $start, $length, $encoding);
8188
    }
8189
8190
    /**
8191
     * Convert a string to e.g.: "snake_case"
8192
     *
8193
     * @param string $str
8194
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
8195
     *
8196
     * @psalm-pure
8197
     *
8198
     * @return string
8199
     *                <p>A string in snake_case.</p>
8200
     */
8201
    public static function str_snakeize(string $str, string $encoding = 'UTF-8'): string
8202
    {
8203 22
        if ($str === '') {
8204
            return '';
8205
        }
8206
8207 22
        $str = \str_replace(
8208 22
            '-',
8209 22
            '_',
8210 22
            self::normalize_whitespace($str)
8211
        );
8212
8213 22
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8214 19
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
8215
        }
8216
8217 22
        $str = (string) \preg_replace_callback(
8218 22
            '/([\\p{N}|\\p{Lu}])/u',
8219
            /**
8220
             * @param string[] $matches
8221
             *
8222
             * @psalm-pure
8223
             *
8224
             * @return string
8225
             */
8226
            static function (array $matches) use ($encoding): string {
8227 9
                $match = $matches[1];
8228 9
                $match_int = (int) $match;
8229
8230 9
                if ((string) $match_int === $match) {
8231 4
                    return '_' . $match . '_';
8232
                }
8233
8234 5
                if ($encoding === 'UTF-8') {
8235 5
                    return '_' . \mb_strtolower($match);
8236
                }
8237
8238
                return '_' . self::strtolower($match, $encoding);
8239 22
            },
8240 22
            $str
8241
        );
8242
8243 22
        $str = (string) \preg_replace(
8244
            [
8245 22
                '/\\s+/u',           // convert spaces to "_"
8246
                '/^\\s+|\\s+$/u', // trim leading & trailing spaces
8247
                '/_+/',                 // remove double "_"
8248
            ],
8249
            [
8250 22
                '_',
8251
                '',
8252
                '_',
8253
            ],
8254 22
            $str
8255
        );
8256
8257 22
        return \trim(\trim($str, '_')); // trim leading & trailing "_" + whitespace
8258
    }
8259
8260
    /**
8261
     * Sort all characters according to code points.
8262
     *
8263
     * EXAMPLE: <code>UTF8::str_sort('  -ABC-中文空白-  '); // '    ---ABC中文白空'</code>
8264
     *
8265
     * @param string $str    <p>A UTF-8 string.</p>
8266
     * @param bool   $unique <p>Sort unique. If <strong>true</strong>, repeated characters are ignored.</p>
8267
     * @param bool   $desc   <p>If <strong>true</strong>, will sort characters in reverse code point order.</p>
8268
     *
8269
     * @psalm-pure
8270
     *
8271
     * @return string
8272
     *                <p>A string of sorted characters.</p>
8273
     */
8274
    public static function str_sort(string $str, bool $unique = false, bool $desc = false): string
8275
    {
8276 2
        $array = self::codepoints($str);
8277
8278 2
        if ($unique) {
8279 2
            $array = \array_flip(\array_flip($array));
8280
        }
8281
8282 2
        if ($desc) {
8283 2
            \arsort($array);
0 ignored issues
show
Bug introduced by
It seems like $array can also be of type null; however, parameter $array of arsort() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

8283
            \arsort(/** @scrutinizer ignore-type */ $array);
Loading history...
8284
        } else {
8285 2
            \asort($array);
0 ignored issues
show
Bug introduced by
It seems like $array can also be of type null; however, parameter $array of asort() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

8285
            \asort(/** @scrutinizer ignore-type */ $array);
Loading history...
8286
        }
8287
8288 2
        return self::string($array);
8289
    }
8290
8291
    /**
8292
     * Convert a string to an array of Unicode characters.
8293
     *
8294
     * EXAMPLE: <code>
8295
     * UTF8::str_split_array(['中文空白', 'test'], 2); // [['中文', '空白'], ['te', 'st']]
8296
     * </code>
8297
     *
8298
     * @param int[]|string[] $input                   <p>The string[] or int[] to split into array.</p>
8299
     * @param int            $length                  [optional] <p>Max character length of each array
8300
     *                                                lement.</p>
8301
     * @param bool           $clean_utf8              [optional] <p>Remove non UTF-8 chars from the
8302
     *                                                string.</p>
8303
     * @param bool           $try_to_use_mb_functions [optional] <p>Set to false, if you don't want to use
8304
     *                                                "mb_substr"</p>
8305
     *
8306
     * @psalm-pure
8307
     *
8308
     * @return string[][]
8309
     *                    <p>An array containing chunks of the input.</p>
8310
     */
8311
    public static function str_split_array(
8312
        array $input,
8313
        int $length = 1,
8314
        bool $clean_utf8 = false,
8315
        bool $try_to_use_mb_functions = true
8316
    ): array {
8317 1
        foreach ($input as $k => &$v) {
8318 1
            $v = self::str_split(
8319 1
                $v,
8320 1
                $length,
8321 1
                $clean_utf8,
8322 1
                $try_to_use_mb_functions
8323
            );
8324
        }
8325
8326
        /** @var string[][] $input */
8327 1
        return $input;
8328
    }
8329
8330
    /**
8331
     * Convert a string to an array of unicode characters.
8332
     *
8333
     * EXAMPLE: <code>UTF8::str_split('中文空白'); // array('中', '文', '空', '白')</code>
8334
     *
8335
     * @param int|string $input                   <p>The string or int to split into array.</p>
8336
     * @param int        $length                  [optional] <p>Max character length of each array
8337
     *                                            element.</p>
8338
     * @param bool       $clean_utf8              [optional] <p>Remove non UTF-8 chars from the
8339
     *                                            string.</p>
8340
     * @param bool       $try_to_use_mb_functions [optional] <p>Set to false, if you don't want to use
8341
     *                                            "mb_substr"</p>
8342
     *
8343
     * @psalm-pure
8344
     *
8345
     * @return string[]
8346
     *                  <p>An array containing chunks of chars from the input.</p>
8347
     *
8348
     * @noinspection SuspiciousBinaryOperationInspection
8349
     * @noinspection OffsetOperationsInspection
8350
     */
8351
    public static function str_split(
8352
        $input,
8353
        int $length = 1,
8354
        bool $clean_utf8 = false,
8355
        bool $try_to_use_mb_functions = true
8356
    ): array {
8357 90
        if ($length <= 0) {
8358 3
            return [];
8359
        }
8360
8361
        // this is only an old fallback
8362
        /** @noinspection PhpSillyAssignmentInspection - hack for phpstan */
8363
        /** @var int|int[]|string|string[] $input */
8364 89
        $input = $input;
8365 89
        if (\is_array($input)) {
8366
            /**
8367
             * @psalm-suppress InvalidReturnStatement
8368
             */
8369
            return self::str_split_array(
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::str_split_a...ry_to_use_mb_functions) returns the type array<mixed,string[]> which is incompatible with the documented return type string[].
Loading history...
8370
                $input,
8371
                $length,
8372
                $clean_utf8,
8373
                $try_to_use_mb_functions
8374
            );
8375
        }
8376
8377
        // init
8378 89
        $input = (string) $input;
8379
8380 89
        if ($input === '') {
8381 14
            return [];
8382
        }
8383
8384 86
        if ($clean_utf8) {
8385 19
            $input = self::clean($input);
8386
        }
8387
8388
        if (
8389 86
            $try_to_use_mb_functions
8390
            &&
8391 86
            self::$SUPPORT['mbstring'] === true
8392
        ) {
8393 82
            if (\function_exists('mb_str_split')) {
8394
                /**
8395
                 * @psalm-suppress ImpureFunctionCall - why?
8396
                 */
8397 82
                $return = \mb_str_split($input, $length);
8398 82
                if ($return !== false) {
8399 82
                    return $return;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $return returns an array which contains values of type array which are incompatible with the documented value type string.
Loading history...
8400
                }
8401
            }
8402
8403
            $i_max = \mb_strlen($input);
8404
            if ($i_max <= 127) {
8405
                $ret = [];
8406
                for ($i = 0; $i < $i_max; ++$i) {
8407
                    $ret[] = \mb_substr($input, $i, 1);
8408
                }
8409
            } else {
8410
                $return_array = [];
8411
                \preg_match_all('/./us', $input, $return_array);
8412
                $ret = $return_array[0] ?? [];
8413
            }
8414 23
        } elseif (self::$SUPPORT['pcre_utf8'] === true) {
8415 17
            $return_array = [];
8416 17
            \preg_match_all('/./us', $input, $return_array);
8417 17
            $ret = $return_array[0] ?? [];
8418
        } else {
8419
8420
            // fallback
8421
8422 8
            $ret = [];
8423 8
            $len = \strlen($input);
8424
8425
            /** @noinspection ForeachInvariantsInspection */
8426 8
            for ($i = 0; $i < $len; ++$i) {
8427 8
                if (($input[$i] & "\x80") === "\x00") {
8428 8
                    $ret[] = $input[$i];
8429
                } elseif (
8430 8
                    isset($input[$i + 1])
8431
                    &&
8432 8
                    ($input[$i] & "\xE0") === "\xC0"
8433
                ) {
8434 4
                    if (($input[$i + 1] & "\xC0") === "\x80") {
8435 4
                        $ret[] = $input[$i] . $input[$i + 1];
8436
8437 4
                        ++$i;
8438
                    }
8439
                } elseif (
8440 6
                    isset($input[$i + 2])
8441
                    &&
8442 6
                    ($input[$i] & "\xF0") === "\xE0"
8443
                ) {
8444
                    if (
8445 6
                        ($input[$i + 1] & "\xC0") === "\x80"
8446
                        &&
8447 6
                        ($input[$i + 2] & "\xC0") === "\x80"
8448
                    ) {
8449 6
                        $ret[] = $input[$i] . $input[$i + 1] . $input[$i + 2];
8450
8451 6
                        $i += 2;
8452
                    }
8453
                } elseif (
8454
                    isset($input[$i + 3])
8455
                    &&
8456
                    ($input[$i] & "\xF8") === "\xF0"
8457
                ) {
8458
                    if (
8459
                        ($input[$i + 1] & "\xC0") === "\x80"
8460
                        &&
8461
                        ($input[$i + 2] & "\xC0") === "\x80"
8462
                        &&
8463
                        ($input[$i + 3] & "\xC0") === "\x80"
8464
                    ) {
8465
                        $ret[] = $input[$i] . $input[$i + 1] . $input[$i + 2] . $input[$i + 3];
8466
8467
                        $i += 3;
8468
                    }
8469
                }
8470
            }
8471
        }
8472
8473 23
        if ($length > 1) {
8474 2
            $ret = \array_chunk($ret, $length);
8475
8476 2
            return \array_map(
8477
                static function (array $item): string {
8478 2
                    return \implode('', $item);
8479 2
                },
8480 2
                $ret
8481
            );
8482
        }
8483
8484 23
        if (isset($ret[0]) && $ret[0] === '') {
8485
            return [];
8486
        }
8487
8488 23
        return $ret;
8489
    }
8490
8491
    /**
8492
     * Splits the string with the provided regular expression, returning an
8493
     * array of strings. An optional integer $limit will truncate the
8494
     * results.
8495
     *
8496
     * @param string $str
8497
     * @param string $pattern <p>The regex with which to split the string.</p>
8498
     * @param int    $limit   [optional] <p>Maximum number of results to return. Default: -1 === no limit</p>
8499
     *
8500
     * @psalm-pure
8501
     *
8502
     * @return string[]
8503
     *                  <p>An array of strings.</p>
8504
     */
8505
    public static function str_split_pattern(string $str, string $pattern, int $limit = -1): array
8506
    {
8507 16
        if ($limit === 0) {
8508 2
            return [];
8509
        }
8510
8511 14
        if ($pattern === '') {
8512 1
            return [$str];
8513
        }
8514
8515 13
        if (self::$SUPPORT['mbstring'] === true) {
8516 13
            if ($limit >= 0) {
8517
                /** @noinspection PhpComposerExtensionStubsInspection */
8518 8
                $result_tmp = \mb_split($pattern, $str);
8519
8520 8
                $result = [];
8521 8
                foreach ($result_tmp as $item_tmp) {
8522 8
                    if ($limit === 0) {
8523 4
                        break;
8524
                    }
8525 8
                    --$limit;
8526
8527 8
                    $result[] = $item_tmp;
8528
                }
8529
8530 8
                return $result;
8531
            }
8532
8533
            /** @noinspection PhpComposerExtensionStubsInspection */
8534 5
            return \mb_split($pattern, $str);
8535
        }
8536
8537
        if ($limit > 0) {
8538
            ++$limit;
8539
        } else {
8540
            $limit = -1;
8541
        }
8542
8543
        $array = \preg_split('/' . \preg_quote($pattern, '/') . '/u', $str, $limit);
8544
8545
        if ($array === false) {
8546
            return [];
8547
        }
8548
8549
        if ($limit > 0 && \count($array) === $limit) {
8550
            \array_pop($array);
8551
        }
8552
8553
        return $array;
8554
    }
8555
8556
    /**
8557
     * Check if the string starts with the given substring.
8558
     *
8559
     * EXAMPLE: <code>
8560
     * UTF8::str_starts_with('ΚόσμεMiddleEnd', 'Κόσμε'); // true
8561
     * UTF8::str_starts_with('ΚόσμεMiddleEnd', 'κόσμε'); // false
8562
     * </code>
8563
     *
8564
     * @param string $haystack <p>The string to search in.</p>
8565
     * @param string $needle   <p>The substring to search for.</p>
8566
     *
8567
     * @psalm-pure
8568
     *
8569
     * @return bool
8570
     */
8571
    public static function str_starts_with(string $haystack, string $needle): bool
8572
    {
8573 19
        if ($needle === '') {
8574 2
            return true;
8575
        }
8576
8577 19
        if ($haystack === '') {
8578
            return false;
8579
        }
8580
8581 19
        if (\PHP_VERSION_ID >= 80000) {
8582
            /** @phpstan-ignore-next-line - only for PHP8 */
8583
            return \str_starts_with($haystack, $needle);
0 ignored issues
show
Bug introduced by
The function str_starts_with was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

8583
            return /** @scrutinizer ignore-call */ \str_starts_with($haystack, $needle);
Loading history...
8584
        }
8585
8586 19
        return \strncmp($haystack, $needle, \strlen($needle)) === 0;
8587
    }
8588
8589
    /**
8590
     * Returns true if the string begins with any of $substrings, false otherwise.
8591
     *
8592
     * - case-sensitive
8593
     *
8594
     * @param string $str        <p>The input string.</p>
8595
     * @param array  $substrings <p>Substrings to look for.</p>
8596
     *
8597
     * @psalm-pure
8598
     *
8599
     * @return bool
8600
     *              <p>Whether or not $str starts with $substring.</p>
8601
     */
8602
    public static function str_starts_with_any(string $str, array $substrings): bool
8603
    {
8604 8
        if ($str === '') {
8605
            return false;
8606
        }
8607
8608 8
        if ($substrings === []) {
8609
            return false;
8610
        }
8611
8612 8
        foreach ($substrings as &$substring) {
8613 8
            if (self::str_starts_with($str, $substring)) {
8614 8
                return true;
8615
            }
8616
        }
8617
8618 6
        return false;
8619
    }
8620
8621
    /**
8622
     * Gets the substring after the first occurrence of a separator.
8623
     *
8624
     * @param string $str       <p>The input string.</p>
8625
     * @param string $separator <p>The string separator.</p>
8626
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
8627
     *
8628
     * @psalm-pure
8629
     *
8630
     * @return string
8631
     */
8632
    public static function str_substr_after_first_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
8633
    {
8634 1
        if ($separator === '' || $str === '') {
8635 1
            return '';
8636
        }
8637
8638 1
        if ($encoding === 'UTF-8') {
8639 1
            $offset = \mb_strpos($str, $separator);
8640 1
            if ($offset === false) {
8641 1
                return '';
8642
            }
8643
8644 1
            return (string) \mb_substr(
8645 1
                $str,
8646 1
                $offset + (int) \mb_strlen($separator)
8647
            );
8648
        }
8649
8650
        $offset = self::strpos($str, $separator, 0, $encoding);
8651
        if ($offset === false) {
8652
            return '';
8653
        }
8654
8655
        return (string) \mb_substr(
8656
            $str,
8657
            $offset + (int) self::strlen($separator, $encoding),
8658
            null,
8659
            $encoding
8660
        );
8661
    }
8662
8663
    /**
8664
     * Gets the substring after the last occurrence of a separator.
8665
     *
8666
     * @param string $str       <p>The input string.</p>
8667
     * @param string $separator <p>The string separator.</p>
8668
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
8669
     *
8670
     * @psalm-pure
8671
     *
8672
     * @return string
8673
     */
8674
    public static function str_substr_after_last_separator(
8675
        string $str,
8676
        string $separator,
8677
        string $encoding = 'UTF-8'
8678
    ): string {
8679 1
        if ($separator === '' || $str === '') {
8680 1
            return '';
8681
        }
8682
8683 1
        if ($encoding === 'UTF-8') {
8684 1
            $offset = \mb_strrpos($str, $separator);
8685 1
            if ($offset === false) {
8686 1
                return '';
8687
            }
8688
8689 1
            return (string) \mb_substr(
8690 1
                $str,
8691 1
                $offset + (int) \mb_strlen($separator)
8692
            );
8693
        }
8694
8695
        $offset = self::strrpos($str, $separator, 0, $encoding);
8696
        if ($offset === false) {
8697
            return '';
8698
        }
8699
8700
        return (string) self::substr(
8701
            $str,
8702
            $offset + (int) self::strlen($separator, $encoding),
8703
            null,
8704
            $encoding
8705
        );
8706
    }
8707
8708
    /**
8709
     * Gets the substring before the first occurrence of a separator.
8710
     *
8711
     * @param string $str       <p>The input string.</p>
8712
     * @param string $separator <p>The string separator.</p>
8713
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
8714
     *
8715
     * @psalm-pure
8716
     *
8717
     * @return string
8718
     */
8719
    public static function str_substr_before_first_separator(
8720
        string $str,
8721
        string $separator,
8722
        string $encoding = 'UTF-8'
8723
    ): string {
8724 1
        if ($separator === '' || $str === '') {
8725 1
            return '';
8726
        }
8727
8728 1
        if ($encoding === 'UTF-8') {
8729 1
            $offset = \mb_strpos($str, $separator);
8730 1
            if ($offset === false) {
8731 1
                return '';
8732
            }
8733
8734 1
            return (string) \mb_substr(
8735 1
                $str,
8736 1
                0,
8737 1
                $offset
8738
            );
8739
        }
8740
8741
        $offset = self::strpos($str, $separator, 0, $encoding);
8742
        if ($offset === false) {
8743
            return '';
8744
        }
8745
8746
        return (string) self::substr(
8747
            $str,
8748
            0,
8749
            $offset,
8750
            $encoding
8751
        );
8752
    }
8753
8754
    /**
8755
     * Gets the substring before the last occurrence of a separator.
8756
     *
8757
     * @param string $str       <p>The input string.</p>
8758
     * @param string $separator <p>The string separator.</p>
8759
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
8760
     *
8761
     * @psalm-pure
8762
     *
8763
     * @return string
8764
     */
8765
    public static function str_substr_before_last_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
8766
    {
8767 1
        if ($separator === '' || $str === '') {
8768 1
            return '';
8769
        }
8770
8771 1
        if ($encoding === 'UTF-8') {
8772 1
            $offset = \mb_strrpos($str, $separator);
8773 1
            if ($offset === false) {
8774 1
                return '';
8775
            }
8776
8777 1
            return (string) \mb_substr(
8778 1
                $str,
8779 1
                0,
8780 1
                $offset
8781
            );
8782
        }
8783
8784
        $offset = self::strrpos($str, $separator, 0, $encoding);
8785
        if ($offset === false) {
8786
            return '';
8787
        }
8788
8789
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
8790
8791
        return (string) self::substr(
8792
            $str,
8793
            0,
8794
            $offset,
8795
            $encoding
8796
        );
8797
    }
8798
8799
    /**
8800
     * Gets the substring after (or before via "$before_needle") the first occurrence of the "$needle".
8801
     *
8802
     * @param string $str           <p>The input string.</p>
8803
     * @param string $needle        <p>The string to look for.</p>
8804
     * @param bool   $before_needle [optional] <p>Default: false</p>
8805
     * @param string $encoding      [optional] <p>Default: 'UTF-8'</p>
8806
     *
8807
     * @psalm-pure
8808
     *
8809
     * @return string
8810
     */
8811
    public static function str_substr_first(
8812
        string $str,
8813
        string $needle,
8814
        bool $before_needle = false,
8815
        string $encoding = 'UTF-8'
8816
    ): string {
8817 2
        if ($str === '' || $needle === '') {
8818 2
            return '';
8819
        }
8820
8821 2
        if ($encoding === 'UTF-8') {
8822 2
            if ($before_needle) {
8823 1
                $part = \mb_strstr(
8824 1
                    $str,
8825 1
                    $needle,
8826 1
                    $before_needle
8827
                );
8828
            } else {
8829 1
                $part = \mb_strstr(
8830 1
                    $str,
8831 2
                    $needle
8832
                );
8833
            }
8834
        } else {
8835
            $part = self::strstr(
8836
                $str,
8837
                $needle,
8838
                $before_needle,
8839
                $encoding
8840
            );
8841
        }
8842
8843 2
        return $part === false ? '' : $part;
8844
    }
8845
8846
    /**
8847
     * Gets the substring after (or before via "$before_needle") the last occurrence of the "$needle".
8848
     *
8849
     * @param string $str           <p>The input string.</p>
8850
     * @param string $needle        <p>The string to look for.</p>
8851
     * @param bool   $before_needle [optional] <p>Default: false</p>
8852
     * @param string $encoding      [optional] <p>Default: 'UTF-8'</p>
8853
     *
8854
     * @psalm-pure
8855
     *
8856
     * @return string
8857
     */
8858
    public static function str_substr_last(
8859
        string $str,
8860
        string $needle,
8861
        bool $before_needle = false,
8862
        string $encoding = 'UTF-8'
8863
    ): string {
8864 2
        if ($str === '' || $needle === '') {
8865 2
            return '';
8866
        }
8867
8868 2
        if ($encoding === 'UTF-8') {
8869 2
            if ($before_needle) {
8870 1
                $part = \mb_strrchr(
8871 1
                    $str,
8872 1
                    $needle,
8873 1
                    $before_needle
8874
                );
8875
            } else {
8876 1
                $part = \mb_strrchr(
8877 1
                    $str,
8878 2
                    $needle
8879
                );
8880
            }
8881
        } else {
8882
            $part = self::strrchr(
8883
                $str,
8884
                $needle,
8885
                $before_needle,
8886
                $encoding
8887
            );
8888
        }
8889
8890 2
        return $part === false ? '' : $part;
8891
    }
8892
8893
    /**
8894
     * Surrounds $str with the given substring.
8895
     *
8896
     * @param string $str
8897
     * @param string $substring <p>The substring to add to both sides.</p>
8898
     *
8899
     * @psalm-pure
8900
     *
8901
     * @return string
8902
     *                <p>A string with the substring both prepended and appended.</p>
8903
     */
8904
    public static function str_surround(string $str, string $substring): string
8905
    {
8906 5
        return $substring . $str . $substring;
8907
    }
8908
8909
    /**
8910
     * Returns a trimmed string with the first letter of each word capitalized.
8911
     * Also accepts an array, $ignore, allowing you to list words not to be
8912
     * capitalized.
8913
     *
8914
     * @param string              $str
8915
     * @param array|string[]|null $ignore                        [optional] <p>An array of words not to capitalize or
8916
     *                                                           null. Default: null</p>
8917
     * @param string              $encoding                      [optional] <p>Default: 'UTF-8'</p>
8918
     * @param bool                $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the
8919
     *                                                           string.</p>
8920
     * @param string|null         $lang                          [optional] <p>Set the language for special cases: az,
8921
     *                                                           el, lt, tr</p>
8922
     * @param bool                $try_to_keep_the_string_length [optional] <p>true === try to keep the string length:
8923
     *                                                           e.g. ẞ -> ß</p>
8924
     * @param bool                $use_trim_first                [optional] <p>true === trim the input string,
8925
     *                                                           first</p>
8926
     * @param string|null         $word_define_chars             [optional] <p>An string of chars that will be used as
8927
     *                                                           whitespace separator === words.</p>
8928
     *
8929
     * @psalm-pure
8930
     *
8931
     * @return string
8932
     *                <p>The titleized string.</p>
8933
     *
8934
     * @noinspection PhpTooManyParametersInspection
8935
     */
8936
    public static function str_titleize(
8937
        string $str,
8938
        array $ignore = null,
8939
        string $encoding = 'UTF-8',
8940
        bool $clean_utf8 = false,
8941
        string $lang = null,
8942
        bool $try_to_keep_the_string_length = false,
8943
        bool $use_trim_first = true,
8944
        string $word_define_chars = null
8945
    ): string {
8946 10
        if ($str === '') {
8947
            return '';
8948
        }
8949
8950 10
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8951 9
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
8952
        }
8953
8954 10
        if ($use_trim_first) {
8955 10
            $str = \trim($str);
8956
        }
8957
8958 10
        if ($clean_utf8) {
8959
            $str = self::clean($str);
8960
        }
8961
8962 10
        $use_mb_functions = $lang === null && !$try_to_keep_the_string_length;
8963
8964 10
        if ($word_define_chars) {
8965 4
            $word_define_chars = \preg_quote($word_define_chars, '/');
8966
        } else {
8967 6
            $word_define_chars = '';
8968
        }
8969
8970 10
        $str = (string) \preg_replace_callback(
8971 10
            '/([^\\s' . $word_define_chars . ']+)/u',
8972
            static function (array $match) use ($try_to_keep_the_string_length, $lang, $ignore, $use_mb_functions, $encoding): string {
8973 10
                if ($ignore !== null && \in_array($match[0], $ignore, true)) {
8974 4
                    return $match[0];
8975
                }
8976
8977 10
                if ($use_mb_functions) {
8978 10
                    if ($encoding === 'UTF-8') {
8979 10
                        return \mb_strtoupper(\mb_substr($match[0], 0, 1))
8980 10
                               . \mb_strtolower(\mb_substr($match[0], 1));
8981
                    }
8982
8983
                    return \mb_strtoupper(\mb_substr($match[0], 0, 1, $encoding), $encoding)
8984
                           . \mb_strtolower(\mb_substr($match[0], 1, null, $encoding), $encoding);
8985
                }
8986
8987
                return self::ucfirst(
8988
                    self::strtolower(
8989
                        $match[0],
8990
                        $encoding,
8991
                        false,
8992
                        $lang,
8993
                        $try_to_keep_the_string_length
8994
                    ),
8995
                    $encoding,
8996
                    false,
8997
                    $lang,
8998
                    $try_to_keep_the_string_length
8999
                );
9000 10
            },
9001 10
            $str
9002
        );
9003
9004 10
        return $str;
9005
    }
9006
9007
    /**
9008
     * Convert a string into a obfuscate string.
9009
     *
9010
     * EXAMPLE: <code>
9011
     *
9012
     * UTF8::str_obfuscate('[email protected]', 0.5, '*', ['@', '.']); // e.g. "l***@m**lleke*.*r*"
9013
     * </code>
9014
     *
9015
     * @param string   $str
9016
     * @param float    $percent
9017
     * @param string   $obfuscateChar
9018
     * @param string[] $keepChars
9019
     *
9020
     * @psalm-pure
9021
     *
9022
     * @return string
9023
     *                <p>The obfuscate string.</p>
9024
     */
9025
    public static function str_obfuscate(
9026
        string $str,
9027
        float $percent = 0.5,
9028
        string $obfuscateChar = '*',
9029
        array $keepChars = []
9030
    ): string {
9031 1
        $obfuscateCharHelper = "\u{2603}";
9032 1
        $str = \str_replace($obfuscateChar, $obfuscateCharHelper, $str);
9033
9034 1
        $chars = self::chars($str);
9035 1
        $charsMax = \count($chars);
9036 1
        $charsMaxChange = \round($charsMax * $percent);
9037 1
        $charsCounter = 0;
9038 1
        $charKeyDone = [];
9039
9040 1
        while ($charsCounter < $charsMaxChange) {
9041 1
            foreach ($chars as $charKey => $char) {
9042 1
                if (isset($charKeyDone[$charKey])) {
9043 1
                    continue;
9044
                }
9045
9046 1
                if (\random_int(0, 100) > 50) {
9047 1
                    continue;
9048
                }
9049
9050 1
                if ($char === $obfuscateChar) {
9051
                    continue;
9052
                }
9053
9054 1
                ++$charsCounter;
9055 1
                $charKeyDone[$charKey] = true;
9056
9057 1
                if ($charsCounter > $charsMaxChange) {
9058
                    break;
9059
                }
9060
9061 1
                if (\in_array($char, $keepChars, true)) {
9062 1
                    continue;
9063
                }
9064
9065 1
                $chars[$charKey] = $obfuscateChar;
9066
            }
9067
        }
9068
9069 1
        $str = \implode('', $chars);
9070
9071 1
        return \str_replace($obfuscateCharHelper, $obfuscateChar, $str);
9072
    }
9073
9074
    /**
9075
     * Returns a trimmed string in proper title case.
9076
     *
9077
     * Also accepts an array, $ignore, allowing you to list words not to be
9078
     * capitalized.
9079
     *
9080
     * Adapted from John Gruber's script.
9081
     *
9082
     * @see https://gist.github.com/gruber/9f9e8650d68b13ce4d78
9083
     *
9084
     * @param string $str
9085
     * @param array  $ignore   <p>An array of words not to capitalize.</p>
9086
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
9087
     *
9088
     * @psalm-pure
9089
     *
9090
     * @return string
9091
     *                <p>The titleized string.</p>
9092
     */
9093
    public static function str_titleize_for_humans(
9094
        string $str,
9095
        array $ignore = [],
9096
        string $encoding = 'UTF-8'
9097
    ): string {
9098 35
        if ($str === '') {
9099
            return '';
9100
        }
9101
9102
        $small_words = [
9103 35
            '(?<!q&)a',
9104
            'an',
9105
            'and',
9106
            'as',
9107
            'at(?!&t)',
9108
            'but',
9109
            'by',
9110
            'en',
9111
            'for',
9112
            'if',
9113
            'in',
9114
            'of',
9115
            'on',
9116
            'or',
9117
            'the',
9118
            'to',
9119
            'v[.]?',
9120
            'via',
9121
            'vs[.]?',
9122
        ];
9123
9124 35
        if ($ignore !== []) {
9125 1
            $small_words = \array_merge($small_words, $ignore);
9126
        }
9127
9128 35
        $small_words_rx = \implode('|', $small_words);
9129 35
        $apostrophe_rx = '(?x: [\'’] [[:lower:]]* )?';
9130
9131 35
        $str = \trim($str);
9132
9133 35
        if (!self::has_lowercase($str)) {
9134 2
            $str = self::strtolower($str, $encoding);
9135
        }
9136
9137
        // the main substitutions
9138
        /** @noinspection RegExpDuplicateAlternationBranch - false-positive - https://youtrack.jetbrains.com/issue/WI-51002 */
9139 35
        $str = (string) \preg_replace_callback(
9140
            '~\\b (_*) (?:                                                           # 1. Leading underscore and
9141
                        ( (?<=[ ][/\\\\]) [[:alpha:]]+ [-_[:alpha:]/\\\\]+ |                # 2. file path or 
9142 35
                          [-_[:alpha:]]+ [@.:] [-_[:alpha:]@.:/]+ ' . $apostrophe_rx . ' )  #    URL, domain, or email
9143
                        |
9144 35
                        ( (?i: ' . $small_words_rx . ' ) ' . $apostrophe_rx . ' )           # 3. or small word (case-insensitive)
9145
                        |
9146 35
                        ( [[:alpha:]] [[:lower:]\'’()\[\]{}]* ' . $apostrophe_rx . ' )     # 4. or word w/o internal caps
9147
                        |
9148 35
                        ( [[:alpha:]] [[:alpha:]\'’()\[\]{}]* ' . $apostrophe_rx . ' )     # 5. or some other word
9149
                      ) (_*) \\b                                                          # 6. With trailing underscore
9150
                    ~ux',
9151
            /**
9152
             * @param string[] $matches
9153
             *
9154
             * @psalm-pure
9155
             *
9156
             * @return string
9157
             */
9158
            static function (array $matches) use ($encoding): string {
9159
                // preserve leading underscore
9160 35
                $str = $matches[1];
9161 35
                if ($matches[2]) {
9162
                    // preserve URLs, domains, emails and file paths
9163 5
                    $str .= $matches[2];
9164 35
                } elseif ($matches[3]) {
9165
                    // lower-case small words
9166 25
                    $str .= self::strtolower($matches[3], $encoding);
9167 35
                } elseif ($matches[4]) {
9168
                    // capitalize word w/o internal caps
9169 34
                    $str .= static::ucfirst($matches[4], $encoding);
9170
                } else {
9171
                    // preserve other kinds of word (iPhone)
9172 7
                    $str .= $matches[5];
9173
                }
9174
                // preserve trailing underscore
9175 35
                $str .= $matches[6];
9176
9177 35
                return $str;
9178 35
            },
9179 35
            $str
9180
        );
9181
9182
        // Exceptions for small words: capitalize at start of title...
9183 35
        $str = (string) \preg_replace_callback(
9184
            '~(  \\A [[:punct:]]*            # start of title...
9185
                      |  [:.;?!][ ]+                # or of subsentence...
9186
                      |  [ ][\'"“‘(\[][ ]* )        # or of inserted subphrase...
9187 35
                      ( ' . $small_words_rx . ' ) \\b # ...followed by small word
9188
                     ~uxi',
9189
            /**
9190
             * @param string[] $matches
9191
             *
9192
             * @psalm-pure
9193
             *
9194
             * @return string
9195
             */
9196
            static function (array $matches) use ($encoding): string {
9197 11
                return $matches[1] . static::ucfirst($matches[2], $encoding);
9198 35
            },
9199 35
            $str
9200
        );
9201
9202
        // ...and end of title
9203 35
        $str = (string) \preg_replace_callback(
9204 35
            '~\\b ( ' . $small_words_rx . ' ) # small word...
9205
                      (?= [[:punct:]]* \Z          # ...at the end of the title...
9206
                      |   [\'"’”)\]] [ ] )         # ...or of an inserted subphrase?
9207
                     ~uxi',
9208
            /**
9209
             * @param string[] $matches
9210
             *
9211
             * @psalm-pure
9212
             *
9213
             * @return string
9214
             */
9215
            static function (array $matches) use ($encoding): string {
9216 3
                return static::ucfirst($matches[1], $encoding);
9217 35
            },
9218 35
            $str
9219
        );
9220
9221
        // Exceptions for small words in hyphenated compound words.
9222
        // e.g. "in-flight" -> In-Flight
9223 35
        $str = (string) \preg_replace_callback(
9224
            '~\\b
9225
                        (?<! -)                   # Negative lookbehind for a hyphen; we do not want to match man-in-the-middle but do want (in-flight)
9226 35
                        ( ' . $small_words_rx . ' )
9227
                        (?= -[[:alpha:]]+)        # lookahead for "-someword"
9228
                       ~uxi',
9229
            /**
9230
             * @param string[] $matches
9231
             *
9232
             * @psalm-pure
9233
             *
9234
             * @return string
9235
             */
9236
            static function (array $matches) use ($encoding): string {
9237
                return static::ucfirst($matches[1], $encoding);
9238 35
            },
9239 35
            $str
9240
        );
9241
9242
        // e.g. "Stand-in" -> "Stand-In" (Stand is already capped at this point)
9243 35
        $str = (string) \preg_replace_callback(
9244
            '~\\b
9245
                      (?<!…)                    # Negative lookbehind for a hyphen; we do not want to match man-in-the-middle but do want (stand-in)
9246
                      ( [[:alpha:]]+- )         # $1 = first word and hyphen, should already be properly capped
9247 35
                      ( ' . $small_words_rx . ' ) # ...followed by small word
9248
                      (?!	- )                 # Negative lookahead for another -
9249
                     ~uxi',
9250
            /**
9251
             * @param string[] $matches
9252
             *
9253
             * @psalm-pure
9254
             *
9255
             * @return string
9256
             */
9257
            static function (array $matches) use ($encoding): string {
9258
                return $matches[1] . static::ucfirst($matches[2], $encoding);
9259 35
            },
9260 35
            $str
9261
        );
9262
9263 35
        return $str;
9264
    }
9265
9266
    /**
9267
     * Get a binary representation of a specific string.
9268
     *
9269
     * EXAPLE: <code>UTF8::str_to_binary('😃'); // '11110000100111111001100010000011'</code>
9270
     *
9271
     * @param string $str <p>The input string.</p>
9272
     *
9273
     * @psalm-pure
9274
     *
9275
     * @return false|string
9276
     *                      <p>false on error</p>
9277
     */
9278
    public static function str_to_binary(string $str)
9279
    {
9280
        /** @var array|false $value - needed for PhpStan (stubs error) */
9281 2
        $value = \unpack('H*', $str);
9282 2
        if ($value === false) {
9283
            return false;
9284
        }
9285
9286
        /** @noinspection OffsetOperationsInspection */
9287 2
        return \base_convert($value[1], 16, 2);
9288
    }
9289
9290
    /**
9291
     * @param string   $str
9292
     * @param bool     $remove_empty_values <p>Remove empty values.</p>
9293
     * @param int|null $remove_short_values <p>The min. string length or null to disable</p>
9294
     *
9295
     * @psalm-pure
9296
     *
9297
     * @return string[]
9298
     */
9299
    public static function str_to_lines(string $str, bool $remove_empty_values = false, int $remove_short_values = null): array
9300
    {
9301 17
        if ($str === '') {
9302 1
            return $remove_empty_values ? [] : [''];
9303
        }
9304
9305 16
        if (self::$SUPPORT['mbstring'] === true) {
9306
            /** @noinspection PhpComposerExtensionStubsInspection */
9307 16
            $return = \mb_split("[\r\n]{1,2}", $str);
9308
        } else {
9309
            $return = \preg_split("/[\r\n]{1,2}/u", $str);
9310
        }
9311
9312 16
        if ($return === false) {
9313
            return $remove_empty_values ? [] : [''];
9314
        }
9315
9316
        if (
9317 16
            $remove_short_values === null
9318
            &&
9319 16
            !$remove_empty_values
9320
        ) {
9321 16
            return $return;
9322
        }
9323
9324
        return self::reduce_string_array(
9325
            $return,
9326
            $remove_empty_values,
9327
            $remove_short_values
9328
        );
9329
    }
9330
9331
    /**
9332
     * Convert a string into an array of words.
9333
     *
9334
     * EXAMPLE: <code>UTF8::str_to_words('中文空白 oöäü#s', '#') // array('', '中文空白', ' ', 'oöäü#s', '')</code>
9335
     *
9336
     * @param string   $str
9337
     * @param string   $char_list           <p>Additional chars for the definition of "words".</p>
9338
     * @param bool     $remove_empty_values <p>Remove empty values.</p>
9339
     * @param int|null $remove_short_values <p>The min. string length or null to disable</p>
9340
     *
9341
     * @psalm-pure
9342
     *
9343
     * @return string[]
9344
     */
9345
    public static function str_to_words(
9346
        string $str,
9347
        string $char_list = '',
9348
        bool $remove_empty_values = false,
9349
        int $remove_short_values = null
9350
    ): array {
9351 13
        if ($str === '') {
9352 4
            return $remove_empty_values ? [] : [''];
9353
        }
9354
9355 13
        $char_list = self::rxClass($char_list, '\pL');
9356
9357 13
        $return = \preg_split("/({$char_list}+(?:[\p{Pd}’']{$char_list}+)*)/u", $str, -1, \PREG_SPLIT_DELIM_CAPTURE);
9358 13
        if ($return === false) {
9359
            return $remove_empty_values ? [] : [''];
9360
        }
9361
9362
        if (
9363 13
            $remove_short_values === null
9364
            &&
9365 13
            !$remove_empty_values
9366
        ) {
9367 13
            return $return;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $return returns an array which contains values of type array which are incompatible with the documented value type string.
Loading history...
9368
        }
9369
9370 2
        $tmp_return = self::reduce_string_array(
9371 2
            $return,
9372 2
            $remove_empty_values,
9373 2
            $remove_short_values
9374
        );
9375
9376 2
        foreach ($tmp_return as &$item) {
9377 2
            $item = (string) $item;
9378
        }
9379
9380 2
        return $tmp_return;
9381
    }
9382
9383
    /**
9384
     * alias for "UTF8::to_ascii()"
9385
     *
9386
     * @param string $str
9387
     * @param string $unknown
9388
     * @param bool   $strict
9389
     *
9390
     * @psalm-pure
9391
     *
9392
     * @return string
9393
     *
9394
     * @see        UTF8::to_ascii()
9395
     * @deprecated <p>please use "UTF8::to_ascii()"</p>
9396
     */
9397
    public static function str_transliterate(
9398
        string $str,
9399
        string $unknown = '?',
9400
        bool $strict = false
9401
    ): string {
9402 7
        return self::to_ascii($str, $unknown, $strict);
9403
    }
9404
9405
    /**
9406
     * Truncates the string to a given length. If $substring is provided, and
9407
     * truncating occurs, the string is further truncated so that the substring
9408
     * may be appended without exceeding the desired length.
9409
     *
9410
     * @param string $str
9411
     * @param int    $length    <p>Desired length of the truncated string.</p>
9412
     * @param string $substring [optional] <p>The substring to append if it can fit. Default: ''</p>
9413
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
9414
     *
9415
     * @psalm-pure
9416
     *
9417
     * @return string
9418
     *                <p>A string after truncating.</p>
9419
     */
9420
    public static function str_truncate(
9421
        string $str,
9422
        int $length,
9423
        string $substring = '',
9424
        string $encoding = 'UTF-8'
9425
    ): string {
9426 22
        if ($str === '') {
9427
            return '';
9428
        }
9429
9430 22
        if ($encoding === 'UTF-8') {
9431 10
            if ($length >= (int) \mb_strlen($str)) {
9432 2
                return $str;
9433
            }
9434
9435 8
            if ($substring !== '') {
9436 4
                $length -= (int) \mb_strlen($substring);
9437
9438
                /** @noinspection UnnecessaryCastingInspection */
9439 4
                return (string) \mb_substr($str, 0, $length) . $substring;
9440
            }
9441
9442
            /** @noinspection UnnecessaryCastingInspection */
9443 4
            return (string) \mb_substr($str, 0, $length);
9444
        }
9445
9446 12
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
9447
9448 12
        if ($length >= (int) self::strlen($str, $encoding)) {
9449 2
            return $str;
9450
        }
9451
9452 10
        if ($substring !== '') {
9453 6
            $length -= (int) self::strlen($substring, $encoding);
9454
        }
9455
9456
        return (
9457 10
               (string) self::substr(
9458 10
                   $str,
9459 10
                   0,
9460 10
                   $length,
9461 10
                   $encoding
9462
               )
9463 10
               ) . $substring;
9464
    }
9465
9466
    /**
9467
     * Truncates the string to a given length, while ensuring that it does not
9468
     * split words. If $substring is provided, and truncating occurs, the
9469
     * string is further truncated so that the substring may be appended without
9470
     * exceeding the desired length.
9471
     *
9472
     * @param string $str
9473
     * @param int    $length                                 <p>Desired length of the truncated string.</p>
9474
     * @param string $substring                              [optional] <p>The substring to append if it can fit.
9475
     *                                                       Default:
9476
     *                                                       ''</p>
9477
     * @param string $encoding                               [optional] <p>Default: 'UTF-8'</p>
9478
     * @param bool   $ignore_do_not_split_words_for_one_word [optional] <p>Default: false</p>
9479
     *
9480
     * @psalm-pure
9481
     *
9482
     * @return string
9483
     *                <p>A string after truncating.</p>
9484
     */
9485
    public static function str_truncate_safe(
9486
        string $str,
9487
        int $length,
9488
        string $substring = '',
9489
        string $encoding = 'UTF-8',
9490
        bool $ignore_do_not_split_words_for_one_word = false
9491
    ): string {
9492 47
        if ($str === '' || $length <= 0) {
9493 1
            return $substring;
9494
        }
9495
9496 47
        if ($encoding === 'UTF-8') {
9497 21
            if ($length >= (int) \mb_strlen($str)) {
9498 5
                return $str;
9499
            }
9500
9501
            // need to further trim the string so we can append the substring
9502 17
            $length -= (int) \mb_strlen($substring);
9503 17
            if ($length <= 0) {
9504 1
                return $substring;
9505
            }
9506
9507
            /** @var false|string $truncated - needed for PhpStan (stubs error) */
9508 17
            $truncated = \mb_substr($str, 0, $length);
9509 17
            if ($truncated === false) {
9510
                return '';
9511
            }
9512
9513
            // if the last word was truncated
9514 17
            $space_position = \mb_strpos($str, ' ', $length - 1);
9515 17
            if ($space_position !== $length) {
9516
                // find pos of the last occurrence of a space, get up to that
9517 13
                $last_position = \mb_strrpos($truncated, ' ', 0);
9518
9519
                if (
9520 13
                    $last_position !== false
9521
                    ||
9522
                    (
9523 3
                        $space_position !== false
9524
                        &&
9525 13
                         !$ignore_do_not_split_words_for_one_word
9526
                    )
9527
                ) {
9528 17
                    $truncated = (string) \mb_substr($truncated, 0, (int) $last_position);
9529
                }
9530
            }
9531
        } else {
9532 26
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
9533
9534 26
            if ($length >= (int) self::strlen($str, $encoding)) {
9535 4
                return $str;
9536
            }
9537
9538
            // need to further trim the string so we can append the substring
9539 22
            $length -= (int) self::strlen($substring, $encoding);
9540 22
            if ($length <= 0) {
9541
                return $substring;
9542
            }
9543
9544 22
            $truncated = self::substr($str, 0, $length, $encoding);
9545
9546 22
            if ($truncated === false) {
9547
                return '';
9548
            }
9549
9550
            // if the last word was truncated
9551 22
            $space_position = self::strpos($str, ' ', $length - 1, $encoding);
9552 22
            if ($space_position !== $length) {
9553
                // find pos of the last occurrence of a space, get up to that
9554 12
                $last_position = self::strrpos($truncated, ' ', 0, $encoding);
9555
9556
                if (
9557 12
                    $last_position !== false
9558
                    ||
9559
                    (
9560 4
                        $space_position !== false
9561
                        &&
9562 12
                        !$ignore_do_not_split_words_for_one_word
9563
                    )
9564
                ) {
9565 9
                    $truncated = (string) self::substr($truncated, 0, (int) $last_position, $encoding);
9566
                }
9567
            }
9568
        }
9569
9570 39
        return $truncated . $substring;
9571
    }
9572
9573
    /**
9574
     * Returns a lowercase and trimmed string separated by underscores.
9575
     * Underscores are inserted before uppercase characters (with the exception
9576
     * of the first character of the string), and in place of spaces as well as
9577
     * dashes.
9578
     *
9579
     * @param string $str
9580
     *
9581
     * @psalm-pure
9582
     *
9583
     * @return string
9584
     *                <p>The underscored string.</p>
9585
     */
9586
    public static function str_underscored(string $str): string
9587
    {
9588 16
        return self::str_delimit($str, '_');
9589
    }
9590
9591
    /**
9592
     * Returns an UpperCamelCase version of the supplied string. It trims
9593
     * surrounding spaces, capitalizes letters following digits, spaces, dashes
9594
     * and underscores, and removes spaces, dashes, underscores.
9595
     *
9596
     * @param string      $str                           <p>The input string.</p>
9597
     * @param string      $encoding                      [optional] <p>Default: 'UTF-8'</p>
9598
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
9599
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
9600
     *                                                   tr</p>
9601
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ
9602
     *                                                   -> ß</p>
9603
     *
9604
     * @psalm-pure
9605
     *
9606
     * @return string
9607
     *                <p>A string in UpperCamelCase.</p>
9608
     */
9609
    public static function str_upper_camelize(
9610
        string $str,
9611
        string $encoding = 'UTF-8',
9612
        bool $clean_utf8 = false,
9613
        string $lang = null,
9614
        bool $try_to_keep_the_string_length = false
9615
    ): string {
9616 13
        return self::ucfirst(self::str_camelize($str, $encoding), $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length);
9617
    }
9618
9619
    /**
9620
     * alias for "UTF8::ucfirst()"
9621
     *
9622
     * @param string      $str
9623
     * @param string      $encoding
9624
     * @param bool        $clean_utf8
9625
     * @param string|null $lang
9626
     * @param bool        $try_to_keep_the_string_length
9627
     *
9628
     * @psalm-pure
9629
     *
9630
     * @return string
9631
     *
9632
     * @see        UTF8::ucfirst()
9633
     * @deprecated <p>please use "UTF8::ucfirst()"</p>
9634
     */
9635
    public static function str_upper_first(
9636
        string $str,
9637
        string $encoding = 'UTF-8',
9638
        bool $clean_utf8 = false,
9639
        string $lang = null,
9640
        bool $try_to_keep_the_string_length = false
9641
    ): string {
9642 5
        return self::ucfirst(
9643 5
            $str,
9644 5
            $encoding,
9645 5
            $clean_utf8,
9646 5
            $lang,
9647 5
            $try_to_keep_the_string_length
9648
        );
9649
    }
9650
9651
    /**
9652
     * Get the number of words in a specific string.
9653
     *
9654
     * EXAMPLES: <code>
9655
     * // format: 0 -> return only word count (int)
9656
     * //
9657
     * UTF8::str_word_count('中文空白 öäü abc#c'); // 4
9658
     * UTF8::str_word_count('中文空白 öäü abc#c', 0, '#'); // 3
9659
     *
9660
     * // format: 1 -> return words (array)
9661
     * //
9662
     * UTF8::str_word_count('中文空白 öäü abc#c', 1); // array('中文空白', 'öäü', 'abc', 'c')
9663
     * UTF8::str_word_count('中文空白 öäü abc#c', 1, '#'); // array('中文空白', 'öäü', 'abc#c')
9664
     *
9665
     * // format: 2 -> return words with offset (array)
9666
     * //
9667
     * UTF8::str_word_count('中文空白 öäü ab#c', 2); // array(0 => '中文空白', 5 => 'öäü', 9 => 'abc', 13 => 'c')
9668
     * UTF8::str_word_count('中文空白 öäü ab#c', 2, '#'); // array(0 => '中文空白', 5 => 'öäü', 9 => 'abc#c')
9669
     * </code>
9670
     *
9671
     * @param string $str       <p>The input string.</p>
9672
     * @param int    $format    [optional] <p>
9673
     *                          <strong>0</strong> => return a number of words (default)<br>
9674
     *                          <strong>1</strong> => return an array of words<br>
9675
     *                          <strong>2</strong> => return an array of words with word-offset as key
9676
     *                          </p>
9677
     * @param string $char_list [optional] <p>Additional chars that contains to words and do not start a new word.</p>
9678
     *
9679
     * @psalm-pure
9680
     *
9681
     * @return int|string[]
9682
     *                      <p>The number of words in the string.</p>
9683
     */
9684
    public static function str_word_count(string $str, int $format = 0, string $char_list = '')
9685
    {
9686 2
        $str_parts = self::str_to_words($str, $char_list);
9687
9688 2
        $len = \count($str_parts);
9689
9690 2
        if ($format === 1) {
9691 2
            $number_of_words = [];
9692 2
            for ($i = 1; $i < $len; $i += 2) {
9693 2
                $number_of_words[] = $str_parts[$i];
9694
            }
9695 2
        } elseif ($format === 2) {
9696 2
            $number_of_words = [];
9697 2
            $offset = (int) self::strlen($str_parts[0]);
9698 2
            for ($i = 1; $i < $len; $i += 2) {
9699 2
                $number_of_words[$offset] = $str_parts[$i];
9700 2
                $offset += (int) self::strlen($str_parts[$i]) + (int) self::strlen($str_parts[$i + 1]);
9701
            }
9702
        } else {
9703 2
            $number_of_words = (int) (($len - 1) / 2);
9704
        }
9705
9706 2
        return $number_of_words;
9707
    }
9708
9709
    /**
9710
     * Case-insensitive string comparison.
9711
     *
9712
     * INFO: Case-insensitive version of UTF8::strcmp()
9713
     *
9714
     * EXAMPLE: <code>UTF8::strcasecmp("iñtërnâtiôn\nàlizætiøn", "Iñtërnâtiôn\nàlizætiøn"); // 0</code>
9715
     *
9716
     * @param string $str1     <p>The first string.</p>
9717
     * @param string $str2     <p>The second string.</p>
9718
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
9719
     *
9720
     * @psalm-pure
9721
     *
9722
     * @return int
9723
     *             <strong>&lt; 0</strong> if str1 is less than str2;<br>
9724
     *             <strong>&gt; 0</strong> if str1 is greater than str2,<br>
9725
     *             <strong>0</strong> if they are equal
9726
     */
9727
    public static function strcasecmp(
9728
        string $str1,
9729
        string $str2,
9730
        string $encoding = 'UTF-8'
9731
    ): int {
9732 23
        return self::strcmp(
9733 23
            self::strtocasefold(
9734 23
                $str1,
9735 23
                true,
9736 23
                false,
9737 23
                $encoding,
9738 23
                null,
9739 23
                false
9740
            ),
9741 23
            self::strtocasefold(
9742 23
                $str2,
9743 23
                true,
9744 23
                false,
9745 23
                $encoding,
9746 23
                null,
9747 23
                false
9748
            )
9749
        );
9750
    }
9751
9752
    /**
9753
     * alias for "UTF8::strstr()"
9754
     *
9755
     * @param string $haystack
9756
     * @param string $needle
9757
     * @param bool   $before_needle
9758
     * @param string $encoding
9759
     * @param bool   $clean_utf8
9760
     *
9761
     * @psalm-pure
9762
     *
9763
     * @return false|string
9764
     *
9765
     * @see        UTF8::strstr()
9766
     * @deprecated <p>please use "UTF8::strstr()"</p>
9767
     */
9768
    public static function strchr(
9769
        string $haystack,
9770
        string $needle,
9771
        bool $before_needle = false,
9772
        string $encoding = 'UTF-8',
9773
        bool $clean_utf8 = false
9774
    ) {
9775 2
        return self::strstr(
9776 2
            $haystack,
9777 2
            $needle,
9778 2
            $before_needle,
9779 2
            $encoding,
9780 2
            $clean_utf8
9781
        );
9782
    }
9783
9784
    /**
9785
     * Case-sensitive string comparison.
9786
     *
9787
     * EXAMPLE: <code>UTF8::strcmp("iñtërnâtiôn\nàlizætiøn", "iñtërnâtiôn\nàlizætiøn"); // 0</code>
9788
     *
9789
     * @param string $str1 <p>The first string.</p>
9790
     * @param string $str2 <p>The second string.</p>
9791
     *
9792
     * @psalm-pure
9793
     *
9794
     * @return int
9795
     *             <strong>&lt; 0</strong> if str1 is less than str2<br>
9796
     *             <strong>&gt; 0</strong> if str1 is greater than str2<br>
9797
     *             <strong>0</strong> if they are equal
9798
     */
9799
    public static function strcmp(string $str1, string $str2): int
9800
    {
9801 29
        if ($str1 === $str2) {
9802 21
            return 0;
9803
        }
9804
9805 24
        return \strcmp(
9806 24
            \Normalizer::normalize($str1, \Normalizer::NFD),
9807 24
            \Normalizer::normalize($str2, \Normalizer::NFD)
9808
        );
9809
    }
9810
9811
    /**
9812
     * Find length of initial segment not matching mask.
9813
     *
9814
     * @param string   $str
9815
     * @param string   $char_list
9816
     * @param int      $offset
9817
     * @param int|null $length
9818
     * @param string   $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
9819
     *
9820
     * @psalm-pure
9821
     *
9822
     * @return int
9823
     */
9824
    public static function strcspn(
9825
        string $str,
9826
        string $char_list,
9827
        int $offset = 0,
9828
        int $length = null,
9829
        string $encoding = 'UTF-8'
9830
    ): int {
9831 12
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9832
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
9833
        }
9834
9835 12
        if ($char_list === '') {
9836 2
            return (int) self::strlen($str, $encoding);
9837
        }
9838
9839 11
        if ($offset || $length !== null) {
9840 3
            if ($encoding === 'UTF-8') {
9841 3
                if ($length === null) {
9842 2
                    $str_tmp = \mb_substr($str, $offset);
9843
                } else {
9844 3
                    $str_tmp = \mb_substr($str, $offset, $length);
9845
                }
9846
            } else {
9847
                $str_tmp = self::substr($str, $offset, $length, $encoding);
9848
            }
9849
9850 3
            if ($str_tmp === false) {
9851
                return 0;
9852
            }
9853
9854
            /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
9855 3
            $str = $str_tmp;
9856
        }
9857
9858 11
        if ($str === '') {
9859 2
            return 0;
9860
        }
9861
9862 10
        $matches = [];
9863 10
        if (\preg_match('/^(.*?)' . self::rxClass($char_list) . '/us', $str, $matches)) {
9864 9
            $return = self::strlen($matches[1], $encoding);
9865 9
            if ($return === false) {
9866
                return 0;
9867
            }
9868
9869 9
            return $return;
9870
        }
9871
9872 2
        return (int) self::strlen($str, $encoding);
9873
    }
9874
9875
    /**
9876
     * alias for "UTF8::stristr()"
9877
     *
9878
     * @param string $haystack
9879
     * @param string $needle
9880
     * @param bool   $before_needle
9881
     * @param string $encoding
9882
     * @param bool   $clean_utf8
9883
     *
9884
     * @psalm-pure
9885
     *
9886
     * @return false|string
9887
     *
9888
     * @see        UTF8::stristr()
9889
     * @deprecated <p>please use "UTF8::stristr()"</p>
9890
     */
9891
    public static function strichr(
9892
        string $haystack,
9893
        string $needle,
9894
        bool $before_needle = false,
9895
        string $encoding = 'UTF-8',
9896
        bool $clean_utf8 = false
9897
    ) {
9898 1
        return self::stristr(
9899 1
            $haystack,
9900 1
            $needle,
9901 1
            $before_needle,
9902 1
            $encoding,
9903 1
            $clean_utf8
9904
        );
9905
    }
9906
9907
    /**
9908
     * Create a UTF-8 string from code points.
9909
     *
9910
     * INFO: opposite to UTF8::codepoints()
9911
     *
9912
     * EXAMPLE: <code>UTF8::string(array(246, 228, 252)); // 'öäü'</code>
9913
     *
9914
     * @param int|int[]|string|string[] $intOrHex <p>Integer or Hexadecimal codepoints.</p>
9915
     *
9916
     * @phpstan-param int[]|numeric-string[]|int|numeric-string $intOrHex
9917
     *
9918
     * @psalm-pure
9919
     *
9920
     * @return string
9921
     *                <p>A UTF-8 encoded string.</p>
9922
     */
9923
    public static function string($intOrHex): string
9924
    {
9925 4
        if ($intOrHex === []) {
9926 4
            return '';
9927
        }
9928
9929 4
        if (!\is_array($intOrHex)) {
9930 1
            $intOrHex = [$intOrHex];
9931
        }
9932
9933 4
        $str = '';
9934 4
        foreach ($intOrHex as $strPart) {
9935 4
            $str .= '&#' . (int) $strPart . ';';
9936
        }
9937
9938 4
        return self::html_entity_decode($str, \ENT_QUOTES | \ENT_HTML5);
9939
    }
9940
9941
    /**
9942
     * Checks if string starts with "BOM" (Byte Order Mark Character) character.
9943
     *
9944
     * EXAMPLE: <code>UTF8::string_has_bom("\xef\xbb\xbf foobar"); // true</code>
9945
     *
9946
     * @param string $str <p>The input string.</p>
9947
     *
9948
     * @psalm-pure
9949
     *
9950
     * @return bool
9951
     *              <p>
9952
     *              <strong>true</strong> if the string has BOM at the start,<br>
9953
     *              <strong>false</strong> otherwise
9954
     *              </p>
9955
     */
9956
    public static function string_has_bom(string $str): bool
9957
    {
9958
        /** @noinspection PhpUnusedLocalVariableInspection */
9959 6
        foreach (self::$BOM as $bom_string => &$bom_byte_length) {
9960 6
            if (\strncmp($str, $bom_string, $bom_byte_length) === 0) {
9961 6
                return true;
9962
            }
9963
        }
9964
9965 6
        return false;
9966
    }
9967
9968
    /**
9969
     * Strip HTML and PHP tags from a string + clean invalid UTF-8.
9970
     *
9971
     * EXAMPLE: <code>UTF8::strip_tags("<span>κόσμε\xa0\xa1</span>"); // 'κόσμε'</code>
9972
     *
9973
     * @see http://php.net/manual/en/function.strip-tags.php
9974
     *
9975
     * @param string      $str            <p>
9976
     *                                    The input string.
9977
     *                                    </p>
9978
     * @param string|null $allowable_tags [optional] <p>
9979
     *                                    You can use the optional second parameter to specify tags which should
9980
     *                                    not be stripped.
9981
     *                                    </p>
9982
     *                                    <p>
9983
     *                                    HTML comments and PHP tags are also stripped. This is hardcoded and
9984
     *                                    can not be changed with allowable_tags.
9985
     *                                    </p>
9986
     * @param bool        $clean_utf8     [optional] <p>Remove non UTF-8 chars from the string.</p>
9987
     *
9988
     * @psalm-pure
9989
     *
9990
     * @return string
9991
     *                <p>The stripped string.</p>
9992
     */
9993
    public static function strip_tags(
9994
        string $str,
9995
        string $allowable_tags = null,
9996
        bool $clean_utf8 = false
9997
    ): string {
9998 4
        if ($str === '') {
9999 1
            return '';
10000
        }
10001
10002 4
        if ($clean_utf8) {
10003 2
            $str = self::clean($str);
10004
        }
10005
10006 4
        if ($allowable_tags === null) {
10007 4
            return \strip_tags($str);
10008
        }
10009
10010 2
        return \strip_tags($str, $allowable_tags);
10011
    }
10012
10013
    /**
10014
     * Strip all whitespace characters. This includes tabs and newline
10015
     * characters, as well as multibyte whitespace such as the thin space
10016
     * and ideographic space.
10017
     *
10018
     * EXAMPLE: <code>UTF8::strip_whitespace('   Ο     συγγραφέας  '); // 'Οσυγγραφέας'</code>
10019
     *
10020
     * @param string $str
10021
     *
10022
     * @psalm-pure
10023
     *
10024
     * @return string
10025
     */
10026
    public static function strip_whitespace(string $str): string
10027
    {
10028 36
        if ($str === '') {
10029 3
            return '';
10030
        }
10031
10032 33
        return (string) \preg_replace('/[[:space:]]+/u', '', $str);
10033
    }
10034
10035
    /**
10036
     * Find the position of the first occurrence of a substring in a string, case-insensitive.
10037
     *
10038
     * INFO: use UTF8::stripos_in_byte() for the byte-length
10039
     *
10040
     * EXAMPLE: <code>UTF8::stripos('aσσb', 'ΣΣ'); // 1</code> (σσ == ΣΣ)
10041
     *
10042
     * @see http://php.net/manual/en/function.mb-stripos.php
10043
     *
10044
     * @param string $haystack   <p>The string from which to get the position of the first occurrence of needle.</p>
10045
     * @param string $needle     <p>The string to find in haystack.</p>
10046
     * @param int    $offset     [optional] <p>The position in haystack to start searching.</p>
10047
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
10048
     * @param bool   $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
10049
     *
10050
     * @psalm-pure
10051
     *
10052
     * @return false|int
10053
     *                   Return the <strong>(int)</strong> numeric position of the first occurrence of needle in the
10054
     *                   haystack string,<br> or <strong>false</strong> if needle is not found
10055
     */
10056
    public static function stripos(
10057
        string $haystack,
10058
        string $needle,
10059
        int $offset = 0,
10060
        string $encoding = 'UTF-8',
10061
        bool $clean_utf8 = false
10062
    ) {
10063 25
        if ($haystack === '') {
10064 5
            if (\PHP_VERSION_ID >= 80000 && $needle === '') {
10065
                return 0;
10066
            }
10067
10068 5
            return false;
10069
        }
10070
10071 24
        if ($needle === '' && \PHP_VERSION_ID < 80000) {
10072 2
            return false;
10073
        }
10074
10075 24
        if ($clean_utf8) {
10076
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
10077
            // if invalid characters are found in $haystack before $needle
10078 1
            $haystack = self::clean($haystack);
10079 1
            $needle = self::clean($needle);
10080
        }
10081
10082 24
        if (self::$SUPPORT['mbstring'] === true) {
10083 24
            if ($encoding === 'UTF-8') {
10084 24
                return \mb_stripos($haystack, $needle, $offset);
10085
            }
10086
10087 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
10088
10089 2
            return \mb_stripos($haystack, $needle, $offset, $encoding);
10090
        }
10091
10092 2
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
10093
10094
        if (
10095 2
            $encoding === 'UTF-8' // INFO: "grapheme_stripos()" can't handle other encodings
10096
            &&
10097 2
            $offset >= 0 // grapheme_stripos() can't handle negative offset
10098
            &&
10099 2
            self::$SUPPORT['intl'] === true
10100
        ) {
10101
            $return_tmp = \grapheme_stripos($haystack, $needle, $offset);
10102
            if ($return_tmp !== false) {
10103
                return $return_tmp;
10104
            }
10105
        }
10106
10107
        //
10108
        // fallback for ascii only
10109
        //
10110
10111 2
        if (ASCII::is_ascii($haystack . $needle)) {
10112 2
            return \stripos($haystack, $needle, $offset);
10113
        }
10114
10115
        //
10116
        // fallback via vanilla php
10117
        //
10118
10119 2
        $haystack = self::strtocasefold($haystack, true, false, $encoding, null, false);
10120 2
        $needle = self::strtocasefold($needle, true, false, $encoding, null, false);
10121
10122 2
        return self::strpos($haystack, $needle, $offset, $encoding);
10123
    }
10124
10125
    /**
10126
     * Returns all of haystack starting from and including the first occurrence of needle to the end.
10127
     *
10128
     * EXAMPLE: <code>
10129
     * $str = 'iñtërnâtiônàlizætiøn';
10130
     * $search = 'NÂT';
10131
     *
10132
     * UTF8::stristr($str, $search)); // 'nâtiônàlizætiøn'
10133
     * UTF8::stristr($str, $search, true)); // 'iñtër'
10134
     * </code>
10135
     *
10136
     * @param string $haystack      <p>The input string. Must be valid UTF-8.</p>
10137
     * @param string $needle        <p>The string to look for. Must be valid UTF-8.</p>
10138
     * @param bool   $before_needle [optional] <p>
10139
     *                              If <b>TRUE</b>, it returns the part of the
10140
     *                              haystack before the first occurrence of the needle (excluding the needle).
10141
     *                              </p>
10142
     * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
10143
     * @param bool   $clean_utf8    [optional] <p>Remove non UTF-8 chars from the string.</p>
10144
     *
10145
     * @psalm-pure
10146
     *
10147
     * @return false|string
10148
     *                      <p>A sub-string,<br>or <strong>false</strong> if needle is not found.</p>
10149
     */
10150
    public static function stristr(
10151
        string $haystack,
10152
        string $needle,
10153
        bool $before_needle = false,
10154
        string $encoding = 'UTF-8',
10155
        bool $clean_utf8 = false
10156
    ) {
10157 13
        if ($haystack === '') {
10158 3
            if (\PHP_VERSION_ID >= 80000 && $needle === '') {
10159
                return '';
10160
            }
10161
10162 3
            return false;
10163
        }
10164
10165 11
        if ($clean_utf8) {
10166
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
10167
            // if invalid characters are found in $haystack before $needle
10168 1
            $needle = self::clean($needle);
10169 1
            $haystack = self::clean($haystack);
10170
        }
10171
10172 11
        if ($needle === '') {
10173 2
            if (\PHP_VERSION_ID >= 80000) {
10174
                return $haystack;
10175
            }
10176
10177 2
            return false;
10178
        }
10179
10180 10
        if (self::$SUPPORT['mbstring'] === true) {
10181 10
            if ($encoding === 'UTF-8') {
10182 10
                return \mb_stristr($haystack, $needle, $before_needle);
10183
            }
10184
10185 1
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
10186
10187 1
            return \mb_stristr($haystack, $needle, $before_needle, $encoding);
10188
        }
10189
10190
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
10191
10192
        if (
10193
            $encoding !== 'UTF-8'
10194
            &&
10195
            self::$SUPPORT['mbstring'] === false
10196
        ) {
10197
            /**
10198
             * @psalm-suppress ImpureFunctionCall - is is only a warning
10199
             */
10200
            \trigger_error('UTF8::stristr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
10201
        }
10202
10203
        if (
10204
            $encoding === 'UTF-8' // INFO: "grapheme_stristr()" can't handle other encodings
10205
            &&
10206
            self::$SUPPORT['intl'] === true
10207
        ) {
10208
            $return_tmp = \grapheme_stristr($haystack, $needle, $before_needle);
10209
            if ($return_tmp !== false) {
10210
                return $return_tmp;
10211
            }
10212
        }
10213
10214
        if (ASCII::is_ascii($needle . $haystack)) {
10215
            return \stristr($haystack, $needle, $before_needle);
10216
        }
10217
10218
        \preg_match('/^(.*?)' . \preg_quote($needle, '/') . '/usi', $haystack, $match);
10219
10220
        if (!isset($match[1])) {
10221
            return false;
10222
        }
10223
10224
        if ($before_needle) {
10225
            return $match[1];
10226
        }
10227
10228
        return self::substr($haystack, (int) self::strlen($match[1], $encoding), null, $encoding);
10229
    }
10230
10231
    /**
10232
     * Get the string length, not the byte-length!
10233
     *
10234
     * INFO: use UTF8::strwidth() for the char-length
10235
     *
10236
     * EXAMPLE: <code>UTF8::strlen("Iñtërnâtiôn\xE9àlizætiøn")); // 20</code>
10237
     *
10238
     * @see http://php.net/manual/en/function.mb-strlen.php
10239
     *
10240
     * @param string $str        <p>The string being checked for length.</p>
10241
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
10242
     * @param bool   $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
10243
     *
10244
     * @psalm-pure
10245
     *
10246
     * @return false|int
10247
     *                   <p>
10248
     *                   The number <strong>(int)</strong> of characters in the string $str having character encoding
10249
     *                   $encoding.
10250
     *                   (One multi-byte character counted as +1).
10251
     *                   <br>
10252
     *                   Can return <strong>false</strong>, if e.g. mbstring is not installed and we process invalid
10253
     *                   chars.
10254
     *                   </p>
10255
     */
10256
    public static function strlen(
10257
        string $str,
10258
        string $encoding = 'UTF-8',
10259
        bool $clean_utf8 = false
10260
    ) {
10261 174
        if ($str === '') {
10262 21
            return 0;
10263
        }
10264
10265 172
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
10266 12
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
10267
        }
10268
10269 172
        if ($clean_utf8) {
10270
            // "mb_strlen" and "\iconv_strlen" returns wrong length,
10271
            // if invalid characters are found in $str
10272 5
            $str = self::clean($str);
10273
        }
10274
10275
        //
10276
        // fallback via mbstring
10277
        //
10278
10279 172
        if (self::$SUPPORT['mbstring'] === true) {
10280 166
            if ($encoding === 'UTF-8') {
10281
                /** @noinspection PhpUsageOfSilenceOperatorInspection - ignore warnings, it's working anyway */
10282 166
                return @\mb_strlen($str);
10283
            }
10284
10285
            /** @noinspection PhpUsageOfSilenceOperatorInspection - ignore warnings, it's working anyway */
10286 4
            return @\mb_strlen($str, $encoding);
10287
        }
10288
10289
        //
10290
        // fallback for binary || ascii only
10291
        //
10292
10293
        if (
10294 8
            $encoding === 'CP850'
10295
            ||
10296 8
            $encoding === 'ASCII'
10297
        ) {
10298
            return \strlen($str);
10299
        }
10300
10301
        if (
10302 8
            $encoding !== 'UTF-8'
10303
            &&
10304 8
            self::$SUPPORT['mbstring'] === false
10305
            &&
10306 8
            self::$SUPPORT['iconv'] === false
10307
        ) {
10308
            /**
10309
             * @psalm-suppress ImpureFunctionCall - is is only a warning
10310
             */
10311 2
            \trigger_error('UTF8::strlen() without mbstring / iconv cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
10312
        }
10313
10314
        //
10315
        // fallback via iconv
10316
        //
10317
10318 8
        if (self::$SUPPORT['iconv'] === true) {
10319
            $return_tmp = \iconv_strlen($str, $encoding);
10320
            if ($return_tmp !== false) {
10321
                return $return_tmp;
10322
            }
10323
        }
10324
10325
        //
10326
        // fallback via intl
10327
        //
10328
10329
        if (
10330 8
            $encoding === 'UTF-8' // INFO: "grapheme_strlen()" can't handle other encodings
10331
            &&
10332 8
            self::$SUPPORT['intl'] === true
10333
        ) {
10334
            $return_tmp = \grapheme_strlen($str);
10335
            if ($return_tmp !== null) {
10336
                return $return_tmp;
10337
            }
10338
        }
10339
10340
        //
10341
        // fallback for ascii only
10342
        //
10343
10344 8
        if (ASCII::is_ascii($str)) {
10345 4
            return \strlen($str);
10346
        }
10347
10348
        //
10349
        // fallback via vanilla php
10350
        //
10351
10352 8
        \preg_match_all('/./us', $str, $parts);
10353
10354 8
        $return_tmp = \count($parts[0]);
10355 8
        if ($return_tmp === 0) {
10356
            return false;
10357
        }
10358
10359 8
        return $return_tmp;
10360
    }
10361
10362
    /**
10363
     * Get string length in byte.
10364
     *
10365
     * @param string $str
10366
     *
10367
     * @psalm-pure
10368
     *
10369
     * @return int
10370
     */
10371
    public static function strlen_in_byte(string $str): int
10372
    {
10373 1
        if ($str === '') {
10374
            return 0;
10375
        }
10376
10377 1
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
10378
            // "mb_" is available if overload is used, so use it ...
10379
            return \mb_strlen($str, 'CP850'); // 8-BIT
10380
        }
10381
10382 1
        return \strlen($str);
10383
    }
10384
10385
    /**
10386
     * Case-insensitive string comparisons using a "natural order" algorithm.
10387
     *
10388
     * INFO: natural order version of UTF8::strcasecmp()
10389
     *
10390
     * EXAMPLES: <code>
10391
     * UTF8::strnatcasecmp('2', '10Hello WORLD 中文空白!'); // -1
10392
     * UTF8::strcasecmp('2Hello world 中文空白!', '10Hello WORLD 中文空白!'); // 1
10393
     *
10394
     * UTF8::strnatcasecmp('10Hello world 中文空白!', '2Hello WORLD 中文空白!'); // 1
10395
     * UTF8::strcasecmp('10Hello world 中文空白!', '2Hello WORLD 中文空白!'); // -1
10396
     * </code>
10397
     *
10398
     * @param string $str1     <p>The first string.</p>
10399
     * @param string $str2     <p>The second string.</p>
10400
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
10401
     *
10402
     * @psalm-pure
10403
     *
10404
     * @return int
10405
     *             <strong>&lt; 0</strong> if str1 is less than str2<br>
10406
     *             <strong>&gt; 0</strong> if str1 is greater than str2<br>
10407
     *             <strong>0</strong> if they are equal
10408
     */
10409
    public static function strnatcasecmp(string $str1, string $str2, string $encoding = 'UTF-8'): int
10410
    {
10411 2
        return self::strnatcmp(
10412 2
            self::strtocasefold($str1, true, false, $encoding, null, false),
10413 2
            self::strtocasefold($str2, true, false, $encoding, null, false)
10414
        );
10415
    }
10416
10417
    /**
10418
     * String comparisons using a "natural order" algorithm
10419
     *
10420
     * INFO: natural order version of UTF8::strcmp()
10421
     *
10422
     * EXAMPLES: <code>
10423
     * UTF8::strnatcmp('2Hello world 中文空白!', '10Hello WORLD 中文空白!'); // -1
10424
     * UTF8::strcmp('2Hello world 中文空白!', '10Hello WORLD 中文空白!'); // 1
10425
     *
10426
     * UTF8::strnatcmp('10Hello world 中文空白!', '2Hello WORLD 中文空白!'); // 1
10427
     * UTF8::strcmp('10Hello world 中文空白!', '2Hello WORLD 中文空白!'); // -1
10428
     * </code>
10429
     *
10430
     * @see http://php.net/manual/en/function.strnatcmp.php
10431
     *
10432
     * @param string $str1 <p>The first string.</p>
10433
     * @param string $str2 <p>The second string.</p>
10434
     *
10435
     * @psalm-pure
10436
     *
10437
     * @return int
10438
     *             <strong>&lt; 0</strong> if str1 is less than str2;<br>
10439
     *             <strong>&gt; 0</strong> if str1 is greater than str2;<br>
10440
     *             <strong>0</strong> if they are equal
10441
     */
10442
    public static function strnatcmp(string $str1, string $str2): int
10443
    {
10444 4
        if ($str1 === $str2) {
10445 4
            return 0;
10446
        }
10447
10448 4
        return \strnatcmp(
10449 4
            (string) self::strtonatfold($str1),
10450 4
            (string) self::strtonatfold($str2)
10451
        );
10452
    }
10453
10454
    /**
10455
     * Case-insensitive string comparison of the first n characters.
10456
     *
10457
     * EXAMPLE: <code>
10458
     * UTF8::strcasecmp("iñtërnâtiôn\nàlizætiøn321", "iñtërnâtiôn\nàlizætiøn123", 5); // 0
10459
     * </code>
10460
     *
10461
     * @see http://php.net/manual/en/function.strncasecmp.php
10462
     *
10463
     * @param string $str1     <p>The first string.</p>
10464
     * @param string $str2     <p>The second string.</p>
10465
     * @param int    $len      <p>The length of strings to be used in the comparison.</p>
10466
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
10467
     *
10468
     * @psalm-pure
10469
     *
10470
     * @return int
10471
     *             <strong>&lt; 0</strong> if <i>str1</i> is less than <i>str2</i>;<br>
10472
     *             <strong>&gt; 0</strong> if <i>str1</i> is greater than <i>str2</i>;<br>
10473
     *             <strong>0</strong> if they are equal
10474
     */
10475
    public static function strncasecmp(
10476
        string $str1,
10477
        string $str2,
10478
        int $len,
10479
        string $encoding = 'UTF-8'
10480
    ): int {
10481 2
        return self::strncmp(
10482 2
            self::strtocasefold($str1, true, false, $encoding, null, false),
10483 2
            self::strtocasefold($str2, true, false, $encoding, null, false),
10484 2
            $len
10485
        );
10486
    }
10487
10488
    /**
10489
     * String comparison of the first n characters.
10490
     *
10491
     * EXAMPLE: <code>
10492
     * UTF8::strncmp("Iñtërnâtiôn\nàlizætiøn321", "Iñtërnâtiôn\nàlizætiøn123", 5); // 0
10493
     * </code>
10494
     *
10495
     * @see http://php.net/manual/en/function.strncmp.php
10496
     *
10497
     * @param string $str1     <p>The first string.</p>
10498
     * @param string $str2     <p>The second string.</p>
10499
     * @param int    $len      <p>Number of characters to use in the comparison.</p>
10500
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
10501
     *
10502
     * @psalm-pure
10503
     *
10504
     * @return int
10505
     *             <strong>&lt; 0</strong> if <i>str1</i> is less than <i>str2</i>;<br>
10506
     *             <strong>&gt; 0</strong> if <i>str1</i> is greater than <i>str2</i>;<br>
10507
     *             <strong>0</strong> if they are equal
10508
     */
10509
    public static function strncmp(
10510
        string $str1,
10511
        string $str2,
10512
        int $len,
10513
        string $encoding = 'UTF-8'
10514
    ): int {
10515 4
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
10516
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
10517
        }
10518
10519 4
        if ($encoding === 'UTF-8') {
10520 4
            $str1 = (string) \mb_substr($str1, 0, $len);
10521 4
            $str2 = (string) \mb_substr($str2, 0, $len);
10522
        } else {
10523
            $str1 = (string) self::substr($str1, 0, $len, $encoding);
10524
            $str2 = (string) self::substr($str2, 0, $len, $encoding);
10525
        }
10526
10527 4
        return self::strcmp($str1, $str2);
10528
    }
10529
10530
    /**
10531
     * Search a string for any of a set of characters.
10532
     *
10533
     * EXAMPLE: <code>UTF8::strpbrk('-中文空白-', '白'); // '白-'</code>
10534
     *
10535
     * @see http://php.net/manual/en/function.strpbrk.php
10536
     *
10537
     * @param string $haystack  <p>The string where char_list is looked for.</p>
10538
     * @param string $char_list <p>This parameter is case-sensitive.</p>
10539
     *
10540
     * @psalm-pure
10541
     *
10542
     * @return false|string
10543
     *                      <p>The string starting from the character found, or false if it is not found.</p>
10544
     */
10545
    public static function strpbrk(string $haystack, string $char_list)
10546
    {
10547 2
        if ($haystack === '' || $char_list === '') {
10548 2
            return false;
10549
        }
10550
10551 2
        if (\preg_match('/' . self::rxClass($char_list) . '/us', $haystack, $m)) {
10552 2
            return \substr($haystack, (int) \strpos($haystack, $m[0]));
10553
        }
10554
10555 2
        return false;
10556
    }
10557
10558
    /**
10559
     * Find the position of the first occurrence of a substring in a string.
10560
     *
10561
     * INFO: use UTF8::strpos_in_byte() for the byte-length
10562
     *
10563
     * EXAMPLE: <code>UTF8::strpos('ABC-ÖÄÜ-中文空白-中文空白', '中'); // 8</code>
10564
     *
10565
     * @see http://php.net/manual/en/function.mb-strpos.php
10566
     *
10567
     * @param string     $haystack   <p>The string from which to get the position of the first occurrence of needle.</p>
10568
     * @param int|string $needle     <p>The string to find in haystack.<br>Or a code point as int.</p>
10569
     * @param int        $offset     [optional] <p>The search offset. If it is not specified, 0 is used.</p>
10570
     * @param string     $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
10571
     * @param bool       $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
10572
     *
10573
     * @psalm-pure
10574
     *
10575
     * @return false|int
10576
     *                   The <strong>(int)</strong> numeric position of the first occurrence of needle in the haystack
10577
     *                   string.<br> If needle is not found it returns false.
10578
     */
10579
    public static function strpos(
10580
        string $haystack,
10581
        $needle,
10582
        int $offset = 0,
10583
        string $encoding = 'UTF-8',
10584
        bool $clean_utf8 = false
10585
    ) {
10586 52
        if ($haystack === '') {
10587 4
            if (\PHP_VERSION_ID >= 80000) {
10588
                if ($needle === '') {
10589
                    return 0;
10590
                }
10591
            } else {
10592 4
                return false;
10593
            }
10594
        }
10595
10596
        // iconv and mbstring do not support integer $needle
10597 51
        if ((int) $needle === $needle) {
10598
            $needle = (string) self::chr($needle);
10599
        }
10600 51
        $needle = (string) $needle;
10601
10602 51
        if ($haystack === '') {
10603
            if (\PHP_VERSION_ID >= 80000 && $needle === '') {
10604
                return 0;
10605
            }
10606
10607
            return false;
10608
        }
10609
10610 51
        if ($needle === '' && \PHP_VERSION_ID < 80000) {
10611 2
            return false;
10612
        }
10613
10614 51
        if ($clean_utf8) {
10615
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
10616
            // if invalid characters are found in $haystack before $needle
10617 3
            $needle = self::clean($needle);
10618 3
            $haystack = self::clean($haystack);
10619
        }
10620
10621 51
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
10622 10
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
10623
        }
10624
10625
        //
10626
        // fallback via mbstring
10627
        //
10628
10629 51
        if (self::$SUPPORT['mbstring'] === true) {
10630 49
            if ($encoding === 'UTF-8') {
10631
                /** @noinspection PhpUsageOfSilenceOperatorInspection - Offset not contained in string */
10632 49
                return @\mb_strpos($haystack, $needle, $offset);
10633
            }
10634
10635
            /** @noinspection PhpUsageOfSilenceOperatorInspection - Offset not contained in string */
10636 2
            return @\mb_strpos($haystack, $needle, $offset, $encoding);
10637
        }
10638
10639
        //
10640
        // fallback for binary || ascii only
10641
        //
10642
        if (
10643 4
            $encoding === 'CP850'
10644
            ||
10645 4
            $encoding === 'ASCII'
10646
        ) {
10647 2
            return \strpos($haystack, $needle, $offset);
10648
        }
10649
10650
        if (
10651 4
            $encoding !== 'UTF-8'
10652
            &&
10653 4
            self::$SUPPORT['iconv'] === false
10654
            &&
10655 4
            self::$SUPPORT['mbstring'] === false
10656
        ) {
10657
            /**
10658
             * @psalm-suppress ImpureFunctionCall - is is only a warning
10659
             */
10660 2
            \trigger_error('UTF8::strpos() without mbstring / iconv cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
10661
        }
10662
10663
        //
10664
        // fallback via intl
10665
        //
10666
10667
        if (
10668 4
            $encoding === 'UTF-8' // INFO: "grapheme_strpos()" can't handle other encodings
10669
            &&
10670 4
            $offset >= 0 // grapheme_strpos() can't handle negative offset
10671
            &&
10672 4
            self::$SUPPORT['intl'] === true
10673
        ) {
10674
            $return_tmp = \grapheme_strpos($haystack, $needle, $offset);
10675
            if ($return_tmp !== false) {
10676
                return $return_tmp;
10677
            }
10678
        }
10679
10680
        //
10681
        // fallback via iconv
10682
        //
10683
10684
        if (
10685 4
            $offset >= 0 // iconv_strpos() can't handle negative offset
10686
            &&
10687 4
            self::$SUPPORT['iconv'] === true
10688
        ) {
10689
            // ignore invalid negative offset to keep compatibility
10690
            // with php < 5.5.35, < 5.6.21, < 7.0.6
10691
            $return_tmp = \iconv_strpos($haystack, $needle, $offset > 0 ? $offset : 0, $encoding);
10692
            if ($return_tmp !== false) {
10693
                return $return_tmp;
10694
            }
10695
        }
10696
10697
        //
10698
        // fallback for ascii only
10699
        //
10700
10701 4
        if (ASCII::is_ascii($haystack . $needle)) {
10702
            /** @noinspection PhpUsageOfSilenceOperatorInspection - Offset not contained in string */
10703 2
            return @\strpos($haystack, $needle, $offset);
10704
        }
10705
10706
        //
10707
        // fallback via vanilla php
10708
        //
10709
10710 4
        $haystack_tmp = self::substr($haystack, $offset, null, $encoding);
10711 4
        if ($haystack_tmp === false) {
10712
            $haystack_tmp = '';
10713
        }
10714 4
        $haystack = (string) $haystack_tmp;
10715
10716 4
        if ($offset < 0) {
10717
            $offset = 0;
10718
        }
10719
10720 4
        $pos = \strpos($haystack, $needle);
10721 4
        if ($pos === false) {
10722 3
            return false;
10723
        }
10724
10725 4
        if ($pos) {
10726 4
            return $offset + (int) self::strlen(\substr($haystack, 0, $pos), $encoding);
10727
        }
10728
10729 2
        return $offset + 0;
10730
    }
10731
10732
    /**
10733
     * Find the position of the first occurrence of a substring in a string.
10734
     *
10735
     * @param string $haystack <p>
10736
     *                         The string being checked.
10737
     *                         </p>
10738
     * @param string $needle   <p>
10739
     *                         The position counted from the beginning of haystack.
10740
     *                         </p>
10741
     * @param int    $offset   [optional] <p>
10742
     *                         The search offset. If it is not specified, 0 is used.
10743
     *                         </p>
10744
     *
10745
     * @psalm-pure
10746
     *
10747
     * @return false|int
10748
     *                   <p>The numeric position of the first occurrence of needle in the
10749
     *                   haystack string. If needle is not found, it returns false.</p>
10750
     */
10751
    public static function strpos_in_byte(string $haystack, string $needle, int $offset = 0)
10752
    {
10753 2
        if ($haystack === '' || $needle === '') {
10754
            return false;
10755
        }
10756
10757 2
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
10758
            // "mb_" is available if overload is used, so use it ...
10759
            return \mb_strpos($haystack, $needle, $offset, 'CP850'); // 8-BIT
10760
        }
10761
10762 2
        return \strpos($haystack, $needle, $offset);
10763
    }
10764
10765
    /**
10766
     * Find the position of the first occurrence of a substring in a string, case-insensitive.
10767
     *
10768
     * @param string $haystack <p>
10769
     *                         The string being checked.
10770
     *                         </p>
10771
     * @param string $needle   <p>
10772
     *                         The position counted from the beginning of haystack.
10773
     *                         </p>
10774
     * @param int    $offset   [optional] <p>
10775
     *                         The search offset. If it is not specified, 0 is used.
10776
     *                         </p>
10777
     *
10778
     * @psalm-pure
10779
     *
10780
     * @return false|int
10781
     *                   <p>The numeric position of the first occurrence of needle in the
10782
     *                   haystack string. If needle is not found, it returns false.</p>
10783
     */
10784
    public static function stripos_in_byte(string $haystack, string $needle, int $offset = 0)
10785
    {
10786 2
        if ($haystack === '' || $needle === '') {
10787
            return false;
10788
        }
10789
10790 2
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
10791
            // "mb_" is available if overload is used, so use it ...
10792
            return \mb_stripos($haystack, $needle, $offset, 'CP850'); // 8-BIT
10793
        }
10794
10795 2
        return \stripos($haystack, $needle, $offset);
10796
    }
10797
10798
    /**
10799
     * Find the last occurrence of a character in a string within another.
10800
     *
10801
     * EXAMPLE: <code>UTF8::strrchr('κόσμεκόσμε-äöü', 'κόσμε'); // 'κόσμε-äöü'</code>
10802
     *
10803
     * @see http://php.net/manual/en/function.mb-strrchr.php
10804
     *
10805
     * @param string $haystack      <p>The string from which to get the last occurrence of needle.</p>
10806
     * @param string $needle        <p>The string to find in haystack</p>
10807
     * @param bool   $before_needle [optional] <p>
10808
     *                              Determines which portion of haystack
10809
     *                              this function returns.
10810
     *                              If set to true, it returns all of haystack
10811
     *                              from the beginning to the last occurrence of needle.
10812
     *                              If set to false, it returns all of haystack
10813
     *                              from the last occurrence of needle to the end,
10814
     *                              </p>
10815
     * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
10816
     * @param bool   $clean_utf8    [optional] <p>Remove non UTF-8 chars from the string.</p>
10817
     *
10818
     * @psalm-pure
10819
     *
10820
     * @return false|string
10821
     *                      <p>The portion of haystack or false if needle is not found.</p>
10822
     */
10823
    public static function strrchr(
10824
        string $haystack,
10825
        string $needle,
10826
        bool $before_needle = false,
10827
        string $encoding = 'UTF-8',
10828
        bool $clean_utf8 = false
10829
    ) {
10830 2
        if ($haystack === '' || $needle === '') {
10831 2
            return false;
10832
        }
10833
10834 2
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
10835 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
10836
        }
10837
10838 2
        if ($clean_utf8) {
10839
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
10840
            // if invalid characters are found in $haystack before $needle
10841 2
            $needle = self::clean($needle);
10842 2
            $haystack = self::clean($haystack);
10843
        }
10844
10845
        //
10846
        // fallback via mbstring
10847
        //
10848
10849 2
        if (self::$SUPPORT['mbstring'] === true) {
10850 2
            if ($encoding === 'UTF-8') {
10851 2
                return \mb_strrchr($haystack, $needle, $before_needle);
10852
            }
10853
10854 2
            return \mb_strrchr($haystack, $needle, $before_needle, $encoding);
10855
        }
10856
10857
        //
10858
        // fallback for binary || ascii only
10859
        //
10860
10861
        if (
10862
            !$before_needle
10863
            &&
10864
            (
10865
                $encoding === 'CP850'
10866
                ||
10867
                $encoding === 'ASCII'
10868
            )
10869
        ) {
10870
            return \strrchr($haystack, $needle);
10871
        }
10872
10873
        if (
10874
            $encoding !== 'UTF-8'
10875
            &&
10876
            self::$SUPPORT['mbstring'] === false
10877
        ) {
10878
            /**
10879
             * @psalm-suppress ImpureFunctionCall - is is only a warning
10880
             */
10881
            \trigger_error('UTF8::strrchr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
10882
        }
10883
10884
        //
10885
        // fallback via iconv
10886
        //
10887
10888
        if (self::$SUPPORT['iconv'] === true) {
10889
            $needle_tmp = self::substr($needle, 0, 1, $encoding);
10890
            if ($needle_tmp === false) {
10891
                return false;
10892
            }
10893
            $needle = (string) $needle_tmp;
10894
10895
            $pos = \iconv_strrpos($haystack, $needle, $encoding);
10896
            if ($pos === false) {
10897
                return false;
10898
            }
10899
10900
            if ($before_needle) {
10901
                return self::substr($haystack, 0, $pos, $encoding);
10902
            }
10903
10904
            return self::substr($haystack, $pos, null, $encoding);
10905
        }
10906
10907
        //
10908
        // fallback via vanilla php
10909
        //
10910
10911
        $needle_tmp = self::substr($needle, 0, 1, $encoding);
10912
        if ($needle_tmp === false) {
10913
            return false;
10914
        }
10915
        $needle = (string) $needle_tmp;
10916
10917
        $pos = self::strrpos($haystack, $needle, 0, $encoding);
10918
        if ($pos === false) {
10919
            return false;
10920
        }
10921
10922
        if ($before_needle) {
10923
            return self::substr($haystack, 0, $pos, $encoding);
10924
        }
10925
10926
        return self::substr($haystack, $pos, null, $encoding);
10927
    }
10928
10929
    /**
10930
     * Reverses characters order in the string.
10931
     *
10932
     * EXAMPLE: <code>UTF8::strrev('κ-öäü'); // 'üäö-κ'</code>
10933
     *
10934
     * @param string $str      <p>The input string.</p>
10935
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
10936
     *
10937
     * @psalm-pure
10938
     *
10939
     * @return string
10940
     *                <p>The string with characters in the reverse sequence.</p>
10941
     */
10942
    public static function strrev(string $str, string $encoding = 'UTF-8'): string
10943
    {
10944 10
        if ($str === '') {
10945 4
            return '';
10946
        }
10947
10948
        // init
10949 8
        $reversed = '';
10950
10951 8
        $str = self::emoji_encode($str, true);
10952
10953 8
        if ($encoding === 'UTF-8') {
10954 8
            if (self::$SUPPORT['intl'] === true) {
10955
                // try "grapheme" first: https://stackoverflow.com/questions/17496493/strrev-dosent-support-utf-8
10956 8
                $i = (int) \grapheme_strlen($str);
10957 8
                while ($i--) {
10958 8
                    $reversed_tmp = \grapheme_substr($str, $i, 1);
10959 8
                    if ($reversed_tmp !== false) {
10960 8
                        $reversed .= $reversed_tmp;
10961
                    }
10962
                }
10963
            } else {
10964
                $i = (int) \mb_strlen($str);
10965 8
                while ($i--) {
10966
                    $reversed_tmp = \mb_substr($str, $i, 1);
10967
                    if ($reversed_tmp !== false) {
10968
                        $reversed .= $reversed_tmp;
10969
                    }
10970
                }
10971
            }
10972
        } else {
10973
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
10974
10975
            $i = (int) self::strlen($str, $encoding);
10976
            while ($i--) {
10977
                $reversed_tmp = self::substr($str, $i, 1, $encoding);
10978
                if ($reversed_tmp !== false) {
10979
                    $reversed .= $reversed_tmp;
10980
                }
10981
            }
10982
        }
10983
10984 8
        return self::emoji_decode($reversed, true);
10985
    }
10986
10987
    /**
10988
     * Find the last occurrence of a character in a string within another, case-insensitive.
10989
     *
10990
     * EXAMPLE: <code>UTF8::strrichr('Aκόσμεκόσμε-äöü', 'aκόσμε'); // 'Aκόσμεκόσμε-äöü'</code>
10991
     *
10992
     * @see http://php.net/manual/en/function.mb-strrichr.php
10993
     *
10994
     * @param string $haystack      <p>The string from which to get the last occurrence of needle.</p>
10995
     * @param string $needle        <p>The string to find in haystack.</p>
10996
     * @param bool   $before_needle [optional] <p>
10997
     *                              Determines which portion of haystack
10998
     *                              this function returns.
10999
     *                              If set to true, it returns all of haystack
11000
     *                              from the beginning to the last occurrence of needle.
11001
     *                              If set to false, it returns all of haystack
11002
     *                              from the last occurrence of needle to the end,
11003
     *                              </p>
11004
     * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
11005
     * @param bool   $clean_utf8    [optional] <p>Remove non UTF-8 chars from the string.</p>
11006
     *
11007
     * @psalm-pure
11008
     *
11009
     * @return false|string
11010
     *                      <p>The portion of haystack or<br>false if needle is not found.</p>
11011
     */
11012
    public static function strrichr(
11013
        string $haystack,
11014
        string $needle,
11015
        bool $before_needle = false,
11016
        string $encoding = 'UTF-8',
11017
        bool $clean_utf8 = false
11018
    ) {
11019 3
        if ($haystack === '' || $needle === '') {
11020 2
            return false;
11021
        }
11022
11023 3
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
11024 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
11025
        }
11026
11027 3
        if ($clean_utf8) {
11028
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
11029
            // if invalid characters are found in $haystack before $needle
11030 2
            $needle = self::clean($needle);
11031 2
            $haystack = self::clean($haystack);
11032
        }
11033
11034
        //
11035
        // fallback via mbstring
11036
        //
11037
11038 3
        if (self::$SUPPORT['mbstring'] === true) {
11039 3
            if ($encoding === 'UTF-8') {
11040 3
                return \mb_strrichr($haystack, $needle, $before_needle);
11041
            }
11042
11043 2
            return \mb_strrichr($haystack, $needle, $before_needle, $encoding);
11044
        }
11045
11046
        //
11047
        // fallback via vanilla php
11048
        //
11049
11050
        $needle_tmp = self::substr($needle, 0, 1, $encoding);
11051
        if ($needle_tmp === false) {
11052
            return false;
11053
        }
11054
        $needle = (string) $needle_tmp;
11055
11056
        $pos = self::strripos($haystack, $needle, 0, $encoding);
11057
        if ($pos === false) {
11058
            return false;
11059
        }
11060
11061
        if ($before_needle) {
11062
            return self::substr($haystack, 0, $pos, $encoding);
11063
        }
11064
11065
        return self::substr($haystack, $pos, null, $encoding);
11066
    }
11067
11068
    /**
11069
     * Find the position of the last occurrence of a substring in a string, case-insensitive.
11070
     *
11071
     * EXAMPLE: <code>UTF8::strripos('ABC-ÖÄÜ-中文空白-中文空白', '中'); // 13</code>
11072
     *
11073
     * @param string     $haystack   <p>The string to look in.</p>
11074
     * @param int|string $needle     <p>The string to look for.</p>
11075
     * @param int        $offset     [optional] <p>Number of characters to ignore in the beginning or end.</p>
11076
     * @param string     $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
11077
     * @param bool       $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
11078
     *
11079
     * @psalm-pure
11080
     *
11081
     * @return false|int
11082
     *                   <p>The <strong>(int)</strong> numeric position of the last occurrence of needle in the haystack
11083
     *                   string.<br>If needle is not found, it returns false.</p>
11084
     */
11085
    public static function strripos(
11086
        string $haystack,
11087
        $needle,
11088
        int $offset = 0,
11089
        string $encoding = 'UTF-8',
11090
        bool $clean_utf8 = false
11091
    ) {
11092 14
        if ($haystack === '') {
11093 3
            if (\PHP_VERSION_ID >= 80000) {
11094
                if ($needle === '') {
11095
                    return 0;
11096
                }
11097
            } else {
11098 3
                return false;
11099
            }
11100
        }
11101
11102
        // iconv and mbstring do not support integer $needle
11103 14
        if ((int) $needle === $needle && $needle >= 0) {
11104
            $needle = (string) self::chr($needle);
11105
        }
11106 14
        $needle = (string) $needle;
11107
11108 14
        if ($haystack === '') {
11109
            if (\PHP_VERSION_ID >= 80000 && $needle === '') {
11110
                return 0;
11111
            }
11112
11113
            return false;
11114
        }
11115
11116 14
        if ($needle === '' && \PHP_VERSION_ID < 80000) {
11117 3
            return false;
11118
        }
11119
11120 14
        if ($clean_utf8) {
11121
            // mb_strripos() && iconv_strripos() is not tolerant to invalid characters
11122 3
            $needle = self::clean($needle);
11123 3
            $haystack = self::clean($haystack);
11124
        }
11125
11126 14
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
11127 9
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
11128
        }
11129
11130
        //
11131
        // fallback via mbstrig
11132
        //
11133
11134 14
        if (self::$SUPPORT['mbstring'] === true) {
11135 14
            if ($encoding === 'UTF-8') {
11136 14
                return \mb_strripos($haystack, $needle, $offset);
11137
            }
11138
11139
            return \mb_strripos($haystack, $needle, $offset, $encoding);
11140
        }
11141
11142
        //
11143
        // fallback for binary || ascii only
11144
        //
11145
11146
        if (
11147
            $encoding === 'CP850'
11148
            ||
11149
            $encoding === 'ASCII'
11150
        ) {
11151
            return \strripos($haystack, $needle, $offset);
11152
        }
11153
11154
        if (
11155
            $encoding !== 'UTF-8'
11156
            &&
11157
            self::$SUPPORT['mbstring'] === false
11158
        ) {
11159
            /**
11160
             * @psalm-suppress ImpureFunctionCall - is is only a warning
11161
             */
11162
            \trigger_error('UTF8::strripos() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
11163
        }
11164
11165
        //
11166
        // fallback via intl
11167
        //
11168
11169
        if (
11170
            $encoding === 'UTF-8' // INFO: "grapheme_strripos()" can't handle other encodings
11171
            &&
11172
            $offset >= 0 // grapheme_strripos() can't handle negative offset
11173
            &&
11174
            self::$SUPPORT['intl'] === true
11175
        ) {
11176
            $return_tmp = \grapheme_strripos($haystack, $needle, $offset);
11177
            if ($return_tmp !== false) {
11178
                return $return_tmp;
11179
            }
11180
        }
11181
11182
        //
11183
        // fallback for ascii only
11184
        //
11185
11186
        if (ASCII::is_ascii($haystack . $needle)) {
11187
            return \strripos($haystack, $needle, $offset);
11188
        }
11189
11190
        //
11191
        // fallback via vanilla php
11192
        //
11193
11194
        $haystack = self::strtocasefold($haystack, true, false, $encoding);
11195
        $needle = self::strtocasefold($needle, true, false, $encoding);
11196
11197
        return self::strrpos($haystack, $needle, $offset, $encoding, $clean_utf8);
11198
    }
11199
11200
    /**
11201
     * Finds position of last occurrence of a string within another, case-insensitive.
11202
     *
11203
     * @param string $haystack <p>
11204
     *                         The string from which to get the position of the last occurrence
11205
     *                         of needle.
11206
     *                         </p>
11207
     * @param string $needle   <p>
11208
     *                         The string to find in haystack.
11209
     *                         </p>
11210
     * @param int    $offset   [optional] <p>
11211
     *                         The position in haystack
11212
     *                         to start searching.
11213
     *                         </p>
11214
     *
11215
     * @psalm-pure
11216
     *
11217
     * @return false|int
11218
     *                   <p>eturn the numeric position of the last occurrence of needle in the
11219
     *                   haystack string, or false if needle is not found.</p>
11220
     */
11221
    public static function strripos_in_byte(string $haystack, string $needle, int $offset = 0)
11222
    {
11223 2
        if ($haystack === '' || $needle === '') {
11224
            return false;
11225
        }
11226
11227 2
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
11228
            // "mb_" is available if overload is used, so use it ...
11229
            return \mb_strripos($haystack, $needle, $offset, 'CP850'); // 8-BIT
11230
        }
11231
11232 2
        return \strripos($haystack, $needle, $offset);
11233
    }
11234
11235
    /**
11236
     * Find the position of the last occurrence of a substring in a string.
11237
     *
11238
     * EXAMPLE: <code>UTF8::strrpos('ABC-ÖÄÜ-中文空白-中文空白', '中'); // 13</code>
11239
     *
11240
     * @see http://php.net/manual/en/function.mb-strrpos.php
11241
     *
11242
     * @param string     $haystack   <p>The string being checked, for the last occurrence of needle</p>
11243
     * @param int|string $needle     <p>The string to find in haystack.<br>Or a code point as int.</p>
11244
     * @param int        $offset     [optional] <p>May be specified to begin searching an arbitrary number of characters
11245
     *                               into the string. Negative values will stop searching at an arbitrary point prior to
11246
     *                               the end of the string.
11247
     *                               </p>
11248
     * @param string     $encoding   [optional] <p>Set the charset.</p>
11249
     * @param bool       $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
11250
     *
11251
     * @psalm-pure
11252
     *
11253
     * @return false|int
11254
     *                   <p>The <strong>(int)</strong> numeric position of the last occurrence of needle in the haystack
11255
     *                   string.<br>If needle is not found, it returns false.</p>
11256
     */
11257
    public static function strrpos(
11258
        string $haystack,
11259
        $needle,
11260
        int $offset = 0,
11261
        string $encoding = 'UTF-8',
11262
        bool $clean_utf8 = false
11263
    ) {
11264 35
        if ($haystack === '') {
11265 4
            if (\PHP_VERSION_ID >= 80000) {
11266
                if ($needle === '') {
11267
                    return 0;
11268
                }
11269
            } else {
11270 4
                return false;
11271
            }
11272
        }
11273
11274
        // iconv and mbstring do not support integer $needle
11275 34
        if ((int) $needle === $needle && $needle >= 0) {
11276 1
            $needle = (string) self::chr($needle);
11277
        }
11278 34
        $needle = (string) $needle;
11279
11280 34
        if ($haystack === '') {
11281
            if (\PHP_VERSION_ID >= 80000 && $needle === '') {
11282
                return 0;
11283
            }
11284
11285
            return false;
11286
        }
11287
11288 34
        if ($needle === '' && \PHP_VERSION_ID < 80000) {
11289 2
            return false;
11290
        }
11291
11292 34
        if ($clean_utf8) {
11293
            // mb_strrpos && iconv_strrpos is not tolerant to invalid characters
11294 4
            $needle = self::clean($needle);
11295 4
            $haystack = self::clean($haystack);
11296
        }
11297
11298 34
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
11299 8
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
11300
        }
11301
11302
        //
11303
        // fallback via mbstring
11304
        //
11305
11306 34
        if (self::$SUPPORT['mbstring'] === true) {
11307 34
            if ($encoding === 'UTF-8') {
11308 34
                return \mb_strrpos($haystack, $needle, $offset);
11309
            }
11310
11311 2
            return \mb_strrpos($haystack, $needle, $offset, $encoding);
11312
        }
11313
11314
        //
11315
        // fallback for binary || ascii only
11316
        //
11317
11318
        if (
11319
            $encoding === 'CP850'
11320
            ||
11321
            $encoding === 'ASCII'
11322
        ) {
11323
            return \strrpos($haystack, $needle, $offset);
11324
        }
11325
11326
        if (
11327
            $encoding !== 'UTF-8'
11328
            &&
11329
            self::$SUPPORT['mbstring'] === false
11330
        ) {
11331
            /**
11332
             * @psalm-suppress ImpureFunctionCall - is is only a warning
11333
             */
11334
            \trigger_error('UTF8::strrpos() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
11335
        }
11336
11337
        //
11338
        // fallback via intl
11339
        //
11340
11341
        if (
11342
            $offset >= 0 // grapheme_strrpos() can't handle negative offset
11343
            &&
11344
            $encoding === 'UTF-8' // INFO: "grapheme_strrpos()" can't handle other encodings
11345
            &&
11346
            self::$SUPPORT['intl'] === true
11347
        ) {
11348
            $return_tmp = \grapheme_strrpos($haystack, $needle, $offset);
11349
            if ($return_tmp !== false) {
11350
                return $return_tmp;
11351
            }
11352
        }
11353
11354
        //
11355
        // fallback for ascii only
11356
        //
11357
11358
        if (ASCII::is_ascii($haystack . $needle)) {
11359
            return \strrpos($haystack, $needle, $offset);
11360
        }
11361
11362
        //
11363
        // fallback via vanilla php
11364
        //
11365
11366
        $haystack_tmp = null;
11367
        if ($offset > 0) {
11368
            $haystack_tmp = self::substr($haystack, $offset);
11369
        } elseif ($offset < 0) {
11370
            $haystack_tmp = self::substr($haystack, 0, $offset);
11371
            $offset = 0;
11372
        }
11373
11374
        if ($haystack_tmp !== null) {
11375
            if ($haystack_tmp === false) {
11376
                $haystack_tmp = '';
11377
            }
11378
            $haystack = (string) $haystack_tmp;
11379
        }
11380
11381
        $pos = \strrpos($haystack, $needle);
11382
        if ($pos === false) {
11383
            return false;
11384
        }
11385
11386
        /** @var false|string $str_tmp - needed for PhpStan (stubs error) */
11387
        $str_tmp = \substr($haystack, 0, $pos);
11388
        if ($str_tmp === false) {
11389
            return false;
11390
        }
11391
11392
        return $offset + (int) self::strlen($str_tmp);
11393
    }
11394
11395
    /**
11396
     * Find the position of the last occurrence of a substring in a string.
11397
     *
11398
     * @param string $haystack <p>
11399
     *                         The string being checked, for the last occurrence
11400
     *                         of needle.
11401
     *                         </p>
11402
     * @param string $needle   <p>
11403
     *                         The string to find in haystack.
11404
     *                         </p>
11405
     * @param int    $offset   [optional] <p>May be specified to begin searching an arbitrary number of characters into
11406
     *                         the string. Negative values will stop searching at an arbitrary point
11407
     *                         prior to the end of the string.
11408
     *                         </p>
11409
     *
11410
     * @psalm-pure
11411
     *
11412
     * @return false|int
11413
     *                   <p>The numeric position of the last occurrence of needle in the
11414
     *                   haystack string. If needle is not found, it returns false.</p>
11415
     */
11416
    public static function strrpos_in_byte(string $haystack, string $needle, int $offset = 0)
11417
    {
11418 2
        if ($haystack === '' || $needle === '') {
11419
            return false;
11420
        }
11421
11422 2
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
11423
            // "mb_" is available if overload is used, so use it ...
11424
            return \mb_strrpos($haystack, $needle, $offset, 'CP850'); // 8-BIT
11425
        }
11426
11427 2
        return \strrpos($haystack, $needle, $offset);
11428
    }
11429
11430
    /**
11431
     * Finds the length of the initial segment of a string consisting entirely of characters contained within a given
11432
     * mask.
11433
     *
11434
     * EXAMPLE: <code>UTF8::strspn('iñtërnâtiônàlizætiøn', 'itñ'); // '3'</code>
11435
     *
11436
     * @param string   $str      <p>The input string.</p>
11437
     * @param string   $mask     <p>The mask of chars</p>
11438
     * @param int      $offset   [optional]
11439
     * @param int|null $length   [optional]
11440
     * @param string   $encoding [optional] <p>Set the charset.</p>
11441
     *
11442
     * @psalm-pure
11443
     *
11444
     * @return false|int
11445
     */
11446
    public static function strspn(
11447
        string $str,
11448
        string $mask,
11449
        int $offset = 0,
11450
        int $length = null,
11451
        string $encoding = 'UTF-8'
11452
    ) {
11453 10
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
11454
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
11455
        }
11456
11457 10
        if ($offset || $length !== null) {
11458 2
            if ($encoding === 'UTF-8') {
11459 2
                if ($length === null) {
11460
                    $str = (string) \mb_substr($str, $offset);
11461
                } else {
11462 2
                    $str = (string) \mb_substr($str, $offset, $length);
11463
                }
11464
            } else {
11465
                $str = (string) self::substr($str, $offset, $length, $encoding);
11466
            }
11467
        }
11468
11469 10
        if ($str === '' || $mask === '') {
11470 2
            return 0;
11471
        }
11472
11473 8
        $matches = [];
11474
11475 8
        return \preg_match('/^' . self::rxClass($mask) . '+/u', $str, $matches) ? (int) self::strlen($matches[0], $encoding) : 0;
11476
    }
11477
11478
    /**
11479
     * Returns part of haystack string from the first occurrence of needle to the end of haystack.
11480
     *
11481
     * EXAMPLE: <code>
11482
     * $str = 'iñtërnâtiônàlizætiøn';
11483
     * $search = 'nât';
11484
     *
11485
     * UTF8::strstr($str, $search)); // 'nâtiônàlizætiøn'
11486
     * UTF8::strstr($str, $search, true)); // 'iñtër'
11487
     * </code>
11488
     *
11489
     * @param string $haystack      <p>The input string. Must be valid UTF-8.</p>
11490
     * @param string $needle        <p>The string to look for. Must be valid UTF-8.</p>
11491
     * @param bool   $before_needle [optional] <p>
11492
     *                              If <b>TRUE</b>, strstr() returns the part of the
11493
     *                              haystack before the first occurrence of the needle (excluding the needle).
11494
     *                              </p>
11495
     * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
11496
     * @param bool   $clean_utf8    [optional] <p>Remove non UTF-8 chars from the string.</p>
11497
     *
11498
     * @psalm-pure
11499
     *
11500
     * @return false|string
11501
     *                      <p>A sub-string,<br>or <strong>false</strong> if needle is not found.</p>
11502
     */
11503
    public static function strstr(
11504
        string $haystack,
11505
        string $needle,
11506
        bool $before_needle = false,
11507
        string $encoding = 'UTF-8',
11508
        bool $clean_utf8 = false
11509
    ) {
11510 3
        if ($haystack === '') {
11511 2
            if (\PHP_VERSION_ID >= 80000 && $needle === '') {
11512
                return '';
11513
            }
11514
11515 2
            return false;
11516
        }
11517
11518 3
        if ($clean_utf8) {
11519
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
11520
            // if invalid characters are found in $haystack before $needle
11521
            $needle = self::clean($needle);
11522
            $haystack = self::clean($haystack);
11523
        }
11524
11525 3
        if ($needle === '') {
11526 1
            if (\PHP_VERSION_ID >= 80000) {
11527
                return $haystack;
11528
            }
11529
11530 1
            return false;
11531
        }
11532
11533 3
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
11534 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
11535
        }
11536
11537
        //
11538
        // fallback via mbstring
11539
        //
11540
11541 3
        if (self::$SUPPORT['mbstring'] === true) {
11542 3
            if ($encoding === 'UTF-8') {
11543 3
                return \mb_strstr($haystack, $needle, $before_needle);
11544
            }
11545
11546 2
            return \mb_strstr($haystack, $needle, $before_needle, $encoding);
11547
        }
11548
11549
        //
11550
        // fallback for binary || ascii only
11551
        //
11552
11553
        if (
11554
            $encoding === 'CP850'
11555
            ||
11556
            $encoding === 'ASCII'
11557
        ) {
11558
            return \strstr($haystack, $needle, $before_needle);
11559
        }
11560
11561
        if (
11562
            $encoding !== 'UTF-8'
11563
            &&
11564
            self::$SUPPORT['mbstring'] === false
11565
        ) {
11566
            /**
11567
             * @psalm-suppress ImpureFunctionCall - is is only a warning
11568
             */
11569
            \trigger_error('UTF8::strstr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
11570
        }
11571
11572
        //
11573
        // fallback via intl
11574
        //
11575
11576
        if (
11577
            $encoding === 'UTF-8' // INFO: "grapheme_strstr()" can't handle other encodings
11578
            &&
11579
            self::$SUPPORT['intl'] === true
11580
        ) {
11581
            $return_tmp = \grapheme_strstr($haystack, $needle, $before_needle);
11582
            if ($return_tmp !== false) {
11583
                return $return_tmp;
11584
            }
11585
        }
11586
11587
        //
11588
        // fallback for ascii only
11589
        //
11590
11591
        if (ASCII::is_ascii($haystack . $needle)) {
11592
            return \strstr($haystack, $needle, $before_needle);
11593
        }
11594
11595
        //
11596
        // fallback via vanilla php
11597
        //
11598
11599
        \preg_match('/^(.*?)' . \preg_quote($needle, '/') . '/us', $haystack, $match);
11600
11601
        if (!isset($match[1])) {
11602
            return false;
11603
        }
11604
11605
        if ($before_needle) {
11606
            return $match[1];
11607
        }
11608
11609
        return self::substr($haystack, (int) self::strlen($match[1]));
11610
    }
11611
11612
    /**
11613
     * Finds first occurrence of a string within another.
11614
     *
11615
     * @param string $haystack      <p>
11616
     *                              The string from which to get the first occurrence
11617
     *                              of needle.
11618
     *                              </p>
11619
     * @param string $needle        <p>
11620
     *                              The string to find in haystack.
11621
     *                              </p>
11622
     * @param bool   $before_needle [optional] <p>
11623
     *                              Determines which portion of haystack
11624
     *                              this function returns.
11625
     *                              If set to true, it returns all of haystack
11626
     *                              from the beginning to the first occurrence of needle.
11627
     *                              If set to false, it returns all of haystack
11628
     *                              from the first occurrence of needle to the end,
11629
     *                              </p>
11630
     *
11631
     * @psalm-pure
11632
     *
11633
     * @return false|string
11634
     *                      <p>The portion of haystack,
11635
     *                      or false if needle is not found.</p>
11636
     */
11637
    public static function strstr_in_byte(
11638
        string $haystack,
11639
        string $needle,
11640
        bool $before_needle = false
11641
    ) {
11642 2
        if ($haystack === '' || $needle === '') {
11643
            return false;
11644
        }
11645
11646 2
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
11647
            // "mb_" is available if overload is used, so use it ...
11648
            return \mb_strstr($haystack, $needle, $before_needle, 'CP850'); // 8-BIT
11649
        }
11650
11651 2
        return \strstr($haystack, $needle, $before_needle);
11652
    }
11653
11654
    /**
11655
     * Unicode transformation for case-less matching.
11656
     *
11657
     * EXAMPLE: <code>UTF8::strtocasefold('ǰ◌̱'); // 'ǰ◌̱'</code>
11658
     *
11659
     * @see http://unicode.org/reports/tr21/tr21-5.html
11660
     *
11661
     * @param string      $str        <p>The input string.</p>
11662
     * @param bool        $full       [optional] <p>
11663
     *                                <b>true</b>, replace full case folding chars (default)<br>
11664
     *                                <b>false</b>, use only limited static array [UTF8::$COMMON_CASE_FOLD]
11665
     *                                </p>
11666
     * @param bool        $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
11667
     * @param string      $encoding   [optional] <p>Set the charset.</p>
11668
     * @param string|null $lang       [optional] <p>Set the language for special cases: az, el, lt, tr</p>
11669
     * @param bool        $lower      [optional] <p>Use lowercase string, otherwise use uppercase string. PS: uppercase
11670
     *                                is for some languages better ...</p>
11671
     *
11672
     * @psalm-pure
11673
     *
11674
     * @return string
11675
     */
11676
    public static function strtocasefold(
11677
        string $str,
11678
        bool $full = true,
11679
        bool $clean_utf8 = false,
11680
        string $encoding = 'UTF-8',
11681
        string $lang = null,
11682
        bool $lower = true
11683
    ): string {
11684 32
        if ($str === '') {
11685 5
            return '';
11686
        }
11687
11688 31
        if ($clean_utf8) {
11689
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
11690
            // if invalid characters are found in $haystack before $needle
11691 2
            $str = self::clean($str);
11692
        }
11693
11694 31
        $str = self::fixStrCaseHelper($str, $lower, $full);
11695
11696 31
        if ($lang === null && $encoding === 'UTF-8') {
11697 31
            if ($lower) {
11698 2
                return \mb_strtolower($str);
11699
            }
11700
11701 29
            return \mb_strtoupper($str);
11702
        }
11703
11704 2
        if ($lower) {
11705
            return self::strtolower($str, $encoding, false, $lang);
11706
        }
11707
11708 2
        return self::strtoupper($str, $encoding, false, $lang);
11709
    }
11710
11711
    /**
11712
     * Make a string lowercase.
11713
     *
11714
     * EXAMPLE: <code>UTF8::strtolower('DÉJÀ Σσς Iıİi'); // 'déjà σσς iıii'</code>
11715
     *
11716
     * @see http://php.net/manual/en/function.mb-strtolower.php
11717
     *
11718
     * @param string      $str                           <p>The string being lowercased.</p>
11719
     * @param string      $encoding                      [optional] <p>Set the charset for e.g. "mb_" function</p>
11720
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
11721
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
11722
     *                                                   tr</p>
11723
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ
11724
     *                                                   -> ß</p>
11725
     *
11726
     * @psalm-pure
11727
     *
11728
     * @return string
11729
     *                <p>String with all alphabetic characters converted to lowercase.</p>
11730
     */
11731
    public static function strtolower(
11732
        $str,
11733
        string $encoding = 'UTF-8',
11734
        bool $clean_utf8 = false,
11735
        string $lang = null,
11736
        bool $try_to_keep_the_string_length = false
11737
    ): string {
11738
        // init
11739 73
        $str = (string) $str;
11740
11741 73
        if ($str === '') {
11742 1
            return '';
11743
        }
11744
11745 72
        if ($clean_utf8) {
11746
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
11747
            // if invalid characters are found in $haystack before $needle
11748 2
            $str = self::clean($str);
11749
        }
11750
11751
        // hack for old php version or for the polyfill ...
11752 72
        if ($try_to_keep_the_string_length) {
11753
            $str = self::fixStrCaseHelper($str, true);
11754
        }
11755
11756 72
        if ($lang === null && $encoding === 'UTF-8') {
11757 13
            return \mb_strtolower($str);
11758
        }
11759
11760 61
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
11761
11762 61
        if ($lang !== null) {
11763 2
            if (self::$SUPPORT['intl'] === true) {
11764 2
                if (self::$INTL_TRANSLITERATOR_LIST === null) {
11765
                    self::$INTL_TRANSLITERATOR_LIST = self::getData('transliterator_list');
11766
                }
11767
11768 2
                $language_code = $lang . '-Lower';
11769 2
                if (!\in_array($language_code, self::$INTL_TRANSLITERATOR_LIST, true)) {
11770
                    /**
11771
                     * @psalm-suppress ImpureFunctionCall - is is only a warning
11772
                     */
11773
                    \trigger_error('UTF8::strtolower() cannot handle special language: ' . $lang . ' | supported: ' . \print_r(self::$INTL_TRANSLITERATOR_LIST, true), \E_USER_WARNING);
11774
11775
                    $language_code = 'Any-Lower';
11776
                }
11777
11778
                /** @noinspection PhpComposerExtensionStubsInspection */
11779
                /** @noinspection UnnecessaryCastingInspection */
11780 2
                return (string) \transliterator_transliterate($language_code, $str);
11781
            }
11782
11783
            /**
11784
             * @psalm-suppress ImpureFunctionCall - is is only a warning
11785
             */
11786
            \trigger_error('UTF8::strtolower() without intl cannot handle the "lang" parameter: ' . $lang, \E_USER_WARNING);
11787
        }
11788
11789
        // always fallback via symfony polyfill
11790 61
        return \mb_strtolower($str, $encoding);
11791
    }
11792
11793
    /**
11794
     * Make a string uppercase.
11795
     *
11796
     * EXAMPLE: <code>UTF8::strtoupper('Déjà Σσς Iıİi'); // 'DÉJÀ ΣΣΣ IIİI'</code>
11797
     *
11798
     * @see http://php.net/manual/en/function.mb-strtoupper.php
11799
     *
11800
     * @param string      $str                           <p>The string being uppercased.</p>
11801
     * @param string      $encoding                      [optional] <p>Set the charset.</p>
11802
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
11803
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
11804
     *                                                   tr</p>
11805
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ
11806
     *                                                   -> ß</p>
11807
     *
11808
     * @psalm-pure
11809
     *
11810
     * @return string
11811
     *                <p>String with all alphabetic characters converted to uppercase.</p>
11812
     */
11813
    public static function strtoupper(
11814
        $str,
11815
        string $encoding = 'UTF-8',
11816
        bool $clean_utf8 = false,
11817
        string $lang = null,
11818
        bool $try_to_keep_the_string_length = false
11819
    ): string {
11820
        // init
11821 17
        $str = (string) $str;
11822
11823 17
        if ($str === '') {
11824 1
            return '';
11825
        }
11826
11827 16
        if ($clean_utf8) {
11828
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
11829
            // if invalid characters are found in $haystack before $needle
11830 2
            $str = self::clean($str);
11831
        }
11832
11833
        // hack for old php version or for the polyfill ...
11834 16
        if ($try_to_keep_the_string_length) {
11835 2
            $str = self::fixStrCaseHelper($str);
11836
        }
11837
11838 16
        if ($lang === null && $encoding === 'UTF-8') {
11839 8
            return \mb_strtoupper($str);
11840
        }
11841
11842 10
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
11843
11844 10
        if ($lang !== null) {
11845 2
            if (self::$SUPPORT['intl'] === true) {
11846 2
                if (self::$INTL_TRANSLITERATOR_LIST === null) {
11847
                    self::$INTL_TRANSLITERATOR_LIST = self::getData('transliterator_list');
11848
                }
11849
11850 2
                $language_code = $lang . '-Upper';
11851 2
                if (!\in_array($language_code, self::$INTL_TRANSLITERATOR_LIST, true)) {
11852
                    /**
11853
                     * @psalm-suppress ImpureFunctionCall - is is only a warning
11854
                     */
11855
                    \trigger_error('UTF8::strtoupper() without intl for special language: ' . $lang, \E_USER_WARNING);
11856
11857
                    $language_code = 'Any-Upper';
11858
                }
11859
11860
                /** @noinspection PhpComposerExtensionStubsInspection */
11861
                /** @noinspection UnnecessaryCastingInspection */
11862 2
                return (string) \transliterator_transliterate($language_code, $str);
11863
            }
11864
11865
            /**
11866
             * @psalm-suppress ImpureFunctionCall - is is only a warning
11867
             */
11868
            \trigger_error('UTF8::strtolower() without intl cannot handle the "lang"-parameter: ' . $lang, \E_USER_WARNING);
11869
        }
11870
11871
        // always fallback via symfony polyfill
11872 10
        return \mb_strtoupper($str, $encoding);
11873
    }
11874
11875
    /**
11876
     * Translate characters or replace sub-strings.
11877
     *
11878
     * EXAMPLE:
11879
     * <code>
11880
     * $array = [
11881
     *     'Hello'   => '○●◎',
11882
     *     '中文空白' => 'earth',
11883
     * ];
11884
     * UTF8::strtr('Hello 中文空白', $array); // '○●◎ earth'
11885
     * </code>
11886
     *
11887
     * @see http://php.net/manual/en/function.strtr.php
11888
     *
11889
     * @param string          $str  <p>The string being translated.</p>
11890
     * @param string|string[] $from <p>The string replacing from.</p>
11891
     * @param string|string[] $to   [optional] <p>The string being translated to to.</p>
11892
     *
11893
     * @psalm-pure
11894
     *
11895
     * @return string
11896
     *                <p>This function returns a copy of str, translating all occurrences of each character in "from"
11897
     *                to the corresponding character in "to".</p>
11898
     */
11899
    public static function strtr(string $str, $from, $to = ''): string
11900
    {
11901 2
        if ($str === '') {
11902
            return '';
11903
        }
11904
11905 2
        if ($from === $to) {
11906
            return $str;
11907
        }
11908
11909 2
        if ($to !== '') {
11910 2
            if (!\is_array($from)) {
11911 2
                $from = self::str_split($from);
11912
            }
11913
11914 2
            if (!\is_array($to)) {
11915 2
                $to = self::str_split($to);
11916
            }
11917
11918 2
            $count_from = \count($from);
11919 2
            $count_to = \count($to);
11920
11921 2
            if ($count_from !== $count_to) {
11922 2
                if ($count_from > $count_to) {
11923 2
                    $from = \array_slice($from, 0, $count_to);
11924 2
                } elseif ($count_from < $count_to) {
11925 2
                    $to = \array_slice($to, 0, $count_from);
11926
                }
11927
            }
11928
11929 2
            $from = \array_combine($from, $to);
11930
            /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
11931 2
            if ($from === false) {
11932
                throw new \InvalidArgumentException('The number of elements for each array isn\'t equal or the arrays are empty: (from: ' . \print_r($from, true) . ' | to: ' . \print_r($to, true) . ')');
11933
            }
11934
        }
11935
11936 2
        if (\is_string($from)) {
11937 2
            return \str_replace($from, $to, $str);
0 ignored issues
show
Bug introduced by
It seems like $to can also be of type array<mixed,array> and array<mixed,string[]>; however, parameter $replace of str_replace() does only seem to accept string|string[], maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

11937
            return \str_replace($from, /** @scrutinizer ignore-type */ $to, $str);
Loading history...
11938
        }
11939
11940 2
        return \strtr($str, $from);
11941
    }
11942
11943
    /**
11944
     * Return the width of a string.
11945
     *
11946
     * INFO: use UTF8::strlen() for the byte-length
11947
     *
11948
     * EXAMPLE: <code>UTF8::strwidth("Iñtërnâtiôn\xE9àlizætiøn")); // 21</code>
11949
     *
11950
     * @param string $str        <p>The input string.</p>
11951
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
11952
     * @param bool   $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
11953
     *
11954
     * @psalm-pure
11955
     *
11956
     * @return int
11957
     */
11958
    public static function strwidth(
11959
        string $str,
11960
        string $encoding = 'UTF-8',
11961
        bool $clean_utf8 = false
11962
    ): int {
11963 2
        if ($str === '') {
11964 2
            return 0;
11965
        }
11966
11967 2
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
11968 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
11969
        }
11970
11971 2
        if ($clean_utf8) {
11972
            // iconv and mbstring are not tolerant to invalid encoding
11973
            // further, their behaviour is inconsistent with that of PHP's substr
11974 2
            $str = self::clean($str);
11975
        }
11976
11977
        //
11978
        // fallback via mbstring
11979
        //
11980
11981 2
        if (self::$SUPPORT['mbstring'] === true) {
11982 2
            if ($encoding === 'UTF-8') {
11983 2
                return \mb_strwidth($str);
11984
            }
11985
11986
            return \mb_strwidth($str, $encoding);
11987
        }
11988
11989
        //
11990
        // fallback via vanilla php
11991
        //
11992
11993
        if ($encoding !== 'UTF-8') {
11994
            $str = self::encode('UTF-8', $str, false, $encoding);
11995
        }
11996
11997
        $wide = 0;
11998
        $str = (string) \preg_replace('/[\x{1100}-\x{115F}\x{2329}\x{232A}\x{2E80}-\x{303E}\x{3040}-\x{A4CF}\x{AC00}-\x{D7A3}\x{F900}-\x{FAFF}\x{FE10}-\x{FE19}\x{FE30}-\x{FE6F}\x{FF00}-\x{FF60}\x{FFE0}-\x{FFE6}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}]/u', '', $str, -1, $wide);
11999
12000
        return ($wide << 1) + (int) self::strlen($str);
12001
    }
12002
12003
    /**
12004
     * Get part of a string.
12005
     *
12006
     * EXAMPLE: <code>UTF8::substr('中文空白', 1, 2); // '文空'</code>
12007
     *
12008
     * @see http://php.net/manual/en/function.mb-substr.php
12009
     *
12010
     * @param string   $str        <p>The string being checked.</p>
12011
     * @param int      $offset     <p>The first position used in str.</p>
12012
     * @param int|null $length     [optional] <p>The maximum length of the returned string.</p>
12013
     * @param string   $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
12014
     * @param bool     $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
12015
     *
12016
     * @psalm-pure
12017
     *
12018
     * @return false|string
12019
     *                      The portion of <i>str</i> specified by the <i>offset</i> and
12020
     *                      <i>length</i> parameters.</p><p>If <i>str</i> is shorter than <i>offset</i>
12021
     *                      characters long, <b>FALSE</b> will be returned.
12022
     */
12023
    public static function substr(
12024
        string $str,
12025
        int $offset = 0,
12026
        int $length = null,
12027
        string $encoding = 'UTF-8',
12028
        bool $clean_utf8 = false
12029
    ) {
12030
        // empty string
12031 172
        if ($str === '' || $length === 0) {
12032 8
            return '';
12033
        }
12034
12035 168
        if ($clean_utf8) {
12036
            // iconv and mbstring are not tolerant to invalid encoding
12037
            // further, their behaviour is inconsistent with that of PHP's substr
12038 2
            $str = self::clean($str);
12039
        }
12040
12041
        // whole string
12042 168
        if (!$offset && $length === null) {
12043 7
            return $str;
12044
        }
12045
12046 163
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
12047 19
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
12048
        }
12049
12050
        //
12051
        // fallback via mbstring
12052
        //
12053
12054 163
        if (self::$SUPPORT['mbstring'] === true && $encoding === 'UTF-8') {
12055 161
            if ($length === null) {
12056 64
                return \mb_substr($str, $offset);
12057
            }
12058
12059 102
            return \mb_substr($str, $offset, $length);
12060
        }
12061
12062
        //
12063
        // fallback for binary || ascii only
12064
        //
12065
12066
        if (
12067 4
            $encoding === 'CP850'
12068
            ||
12069 4
            $encoding === 'ASCII'
12070
        ) {
12071
            if ($length === null) {
12072
                return \substr($str, $offset);
12073
            }
12074
12075
            return \substr($str, $offset, $length);
12076
        }
12077
12078
        // otherwise we need the string-length
12079 4
        $str_length = 0;
12080 4
        if ($offset || $length === null) {
12081 4
            $str_length = self::strlen($str, $encoding);
12082
        }
12083
12084
        // e.g.: invalid chars + mbstring not installed
12085 4
        if ($str_length === false) {
12086
            return false;
12087
        }
12088
12089
        // empty string
12090 4
        if ($offset === $str_length && !$length) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $length of type integer|null is loosely compared to false; this is ambiguous if the integer can be 0. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
12091
            return '';
12092
        }
12093
12094
        // impossible
12095 4
        if ($offset && $offset > $str_length) {
12096
            return '';
12097
        }
12098
12099 4
        $length = $length ?? (int) $str_length;
12100
12101
        if (
12102 4
            $encoding !== 'UTF-8'
12103
            &&
12104 4
            self::$SUPPORT['mbstring'] === false
12105
        ) {
12106
            /**
12107
             * @psalm-suppress ImpureFunctionCall - is is only a warning
12108
             */
12109 2
            \trigger_error('UTF8::substr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
12110
        }
12111
12112
        //
12113
        // fallback via intl
12114
        //
12115
12116
        if (
12117 4
            $encoding === 'UTF-8' // INFO: "grapheme_substr()" can't handle other encodings
12118
            &&
12119 4
            $offset >= 0 // grapheme_substr() can't handle negative offset
12120
            &&
12121 4
            self::$SUPPORT['intl'] === true
12122
        ) {
12123
            $return_tmp = \grapheme_substr($str, $offset, $length);
12124
            if ($return_tmp !== false) {
12125
                return $return_tmp;
12126
            }
12127
        }
12128
12129
        //
12130
        // fallback via iconv
12131
        //
12132
12133
        if (
12134 4
            $length >= 0 // "iconv_substr()" can't handle negative length
12135
            &&
12136 4
            self::$SUPPORT['iconv'] === true
12137
        ) {
12138
            $return_tmp = \iconv_substr($str, $offset, $length);
12139
            if ($return_tmp !== false) {
12140
                return $return_tmp;
12141
            }
12142
        }
12143
12144
        //
12145
        // fallback for ascii only
12146
        //
12147
12148 4
        if (ASCII::is_ascii($str)) {
12149
            return \substr($str, $offset, $length);
12150
        }
12151
12152
        //
12153
        // fallback via vanilla php
12154
        //
12155
12156
        // split to array, and remove invalid characters
12157 4
        $array = self::str_split($str);
12158
12159
        // extract relevant part, and join to make sting again
12160 4
        return \implode('', \array_slice($array, $offset, $length));
12161
    }
12162
12163
    /**
12164
     * Binary-safe comparison of two strings from an offset, up to a length of characters.
12165
     *
12166
     * EXAMPLE: <code>
12167
     * UTF8::substr_compare("○●◎\r", '●◎', 0, 2); // -1
12168
     * UTF8::substr_compare("○●◎\r", '◎●', 1, 2); // 1
12169
     * UTF8::substr_compare("○●◎\r", '●◎', 1, 2); // 0
12170
     * </code>
12171
     *
12172
     * @param string   $str1               <p>The main string being compared.</p>
12173
     * @param string   $str2               <p>The secondary string being compared.</p>
12174
     * @param int      $offset             [optional] <p>The start position for the comparison. If negative, it starts
12175
     *                                     counting from the end of the string.</p>
12176
     * @param int|null $length             [optional] <p>The length of the comparison. The default value is the largest
12177
     *                                     of the length of the str compared to the length of main_str less the
12178
     *                                     offset.</p>
12179
     * @param bool     $case_insensitivity [optional] <p>If case_insensitivity is TRUE, comparison is case
12180
     *                                     insensitive.</p>
12181
     * @param string   $encoding           [optional] <p>Set the charset for e.g. "mb_" function</p>
12182
     *
12183
     * @psalm-pure
12184
     *
12185
     * @return int
12186
     *             <strong>&lt; 0</strong> if str1 is less than str2;<br>
12187
     *             <strong>&gt; 0</strong> if str1 is greater than str2,<br>
12188
     *             <strong>0</strong> if they are equal
12189
     */
12190
    public static function substr_compare(
12191
        string $str1,
12192
        string $str2,
12193
        int $offset = 0,
12194
        int $length = null,
12195
        bool $case_insensitivity = false,
12196
        string $encoding = 'UTF-8'
12197
    ): int {
12198
        if (
12199 2
            $offset !== 0
12200
            ||
12201 2
            $length !== null
12202
        ) {
12203 2
            if ($encoding === 'UTF-8') {
12204 2
                if ($length === null) {
12205 2
                    $str1 = (string) \mb_substr($str1, $offset);
12206
                } else {
12207 2
                    $str1 = (string) \mb_substr($str1, $offset, $length);
12208
                }
12209 2
                $str2 = (string) \mb_substr($str2, 0, (int) self::strlen($str1));
12210
            } else {
12211
                $encoding = self::normalize_encoding($encoding, 'UTF-8');
12212
12213
                $str1 = (string) self::substr($str1, $offset, $length, $encoding);
12214
                $str2 = (string) self::substr($str2, 0, (int) self::strlen($str1), $encoding);
12215
            }
12216
        }
12217
12218 2
        if ($case_insensitivity) {
12219 2
            return self::strcasecmp($str1, $str2, $encoding);
12220
        }
12221
12222 2
        return self::strcmp($str1, $str2);
12223
    }
12224
12225
    /**
12226
     * Count the number of substring occurrences.
12227
     *
12228
     * EXAMPLE: <code>UTF8::substr_count('中文空白', '文空', 1, 2); // 1</code>
12229
     *
12230
     * @see http://php.net/manual/en/function.substr-count.php
12231
     *
12232
     * @param string   $haystack   <p>The string to search in.</p>
12233
     * @param string   $needle     <p>The substring to search for.</p>
12234
     * @param int      $offset     [optional] <p>The offset where to start counting.</p>
12235
     * @param int|null $length     [optional] <p>
12236
     *                             The maximum length after the specified offset to search for the
12237
     *                             substring. It outputs a warning if the offset plus the length is
12238
     *                             greater than the haystack length.
12239
     *                             </p>
12240
     * @param string   $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
12241
     * @param bool     $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
12242
     *
12243
     * @psalm-pure
12244
     *
12245
     * @return false|int
12246
     *                   <p>This functions returns an integer or false if there isn't a string.</p>
12247
     */
12248
    public static function substr_count(
12249
        string $haystack,
12250
        string $needle,
12251
        int $offset = 0,
12252
        int $length = null,
12253
        string $encoding = 'UTF-8',
12254
        bool $clean_utf8 = false
12255
    ) {
12256 5
        if ($needle === '') {
12257 2
            return false;
12258
        }
12259
12260 5
        if ($haystack === '') {
12261 2
            if (\PHP_VERSION_ID >= 80000) {
12262
                return 0;
12263
            }
12264
12265 2
            return 0;
12266
        }
12267
12268 5
        if ($length === 0) {
12269 2
            return 0;
12270
        }
12271
12272 5
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
12273 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
12274
        }
12275
12276 5
        if ($clean_utf8) {
12277
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
12278
            // if invalid characters are found in $haystack before $needle
12279
            $needle = self::clean($needle);
12280
            $haystack = self::clean($haystack);
12281
        }
12282
12283 5
        if ($offset || $length > 0) {
12284 2
            if ($length === null) {
12285 2
                $length_tmp = self::strlen($haystack, $encoding);
12286 2
                if ($length_tmp === false) {
12287
                    return false;
12288
                }
12289 2
                $length = (int) $length_tmp;
12290
            }
12291
12292 2
            if ($encoding === 'UTF-8') {
12293 2
                $haystack = (string) \mb_substr($haystack, $offset, $length);
12294
            } else {
12295 2
                $haystack = (string) \mb_substr($haystack, $offset, $length, $encoding);
12296
            }
12297
        }
12298
12299
        if (
12300 5
            $encoding !== 'UTF-8'
12301
            &&
12302 5
            self::$SUPPORT['mbstring'] === false
12303
        ) {
12304
            /**
12305
             * @psalm-suppress ImpureFunctionCall - is is only a warning
12306
             */
12307
            \trigger_error('UTF8::substr_count() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
12308
        }
12309
12310 5
        if (self::$SUPPORT['mbstring'] === true) {
12311 5
            if ($encoding === 'UTF-8') {
12312 5
                return \mb_substr_count($haystack, $needle);
12313
            }
12314
12315 2
            return \mb_substr_count($haystack, $needle, $encoding);
12316
        }
12317
12318
        \preg_match_all('/' . \preg_quote($needle, '/') . '/us', $haystack, $matches, \PREG_SET_ORDER);
12319
12320
        return \count($matches);
12321
    }
12322
12323
    /**
12324
     * Count the number of substring occurrences.
12325
     *
12326
     * @param string   $haystack <p>
12327
     *                           The string being checked.
12328
     *                           </p>
12329
     * @param string   $needle   <p>
12330
     *                           The string being found.
12331
     *                           </p>
12332
     * @param int      $offset   [optional] <p>
12333
     *                           The offset where to start counting
12334
     *                           </p>
12335
     * @param int|null $length   [optional] <p>
12336
     *                           The maximum length after the specified offset to search for the
12337
     *                           substring. It outputs a warning if the offset plus the length is
12338
     *                           greater than the haystack length.
12339
     *                           </p>
12340
     *
12341
     * @psalm-pure
12342
     *
12343
     * @return false|int
12344
     *                   <p>The number of times the
12345
     *                   needle substring occurs in the
12346
     *                   haystack string.</p>
12347
     */
12348
    public static function substr_count_in_byte(
12349
        string $haystack,
12350
        string $needle,
12351
        int $offset = 0,
12352
        int $length = null
12353
    ) {
12354 4
        if ($haystack === '' || $needle === '') {
12355 1
            return 0;
12356
        }
12357
12358
        if (
12359 3
            ($offset || $length !== null)
12360
            &&
12361 3
            self::$SUPPORT['mbstring_func_overload'] === true
12362
        ) {
12363
            if ($length === null) {
12364
                $length_tmp = self::strlen($haystack);
12365
                if ($length_tmp === false) {
12366
                    return false;
12367
                }
12368
                $length = (int) $length_tmp;
12369
            }
12370
12371
            if (
12372
                (
12373
                    $length !== 0
12374
                    &&
12375
                    $offset !== 0
12376
                )
12377
                &&
12378
                ($length + $offset) <= 0
12379
                &&
12380
                \PHP_VERSION_ID < 71000 // output from "substr_count()" have changed in PHP 7.1
12381
            ) {
12382
                return false;
12383
            }
12384
12385
            /** @var false|string $haystack_tmp - needed for PhpStan (stubs error) */
12386
            $haystack_tmp = \substr($haystack, $offset, $length);
12387
            if ($haystack_tmp === false) {
12388
                $haystack_tmp = '';
12389
            }
12390
            $haystack = (string) $haystack_tmp;
12391
        }
12392
12393 3
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
12394
            // "mb_" is available if overload is used, so use it ...
12395
            return \mb_substr_count($haystack, $needle, 'CP850'); // 8-BIT
12396
        }
12397
12398 3
        if ($length === null) {
12399 3
            return \substr_count($haystack, $needle, $offset);
12400
        }
12401
12402
        return \substr_count($haystack, $needle, $offset, $length);
12403
    }
12404
12405
    /**
12406
     * Returns the number of occurrences of $substring in the given string.
12407
     * By default, the comparison is case-sensitive, but can be made insensitive
12408
     * by setting $case_sensitive to false.
12409
     *
12410
     * @param string $str            <p>The input string.</p>
12411
     * @param string $substring      <p>The substring to search for.</p>
12412
     * @param bool   $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
12413
     * @param string $encoding       [optional] <p>Set the charset for e.g. "mb_" function</p>
12414
     *
12415
     * @psalm-pure
12416
     *
12417
     * @return int
12418
     */
12419
    public static function substr_count_simple(
12420
        string $str,
12421
        string $substring,
12422
        bool $case_sensitive = true,
12423
        string $encoding = 'UTF-8'
12424
    ): int {
12425 15
        if ($str === '' || $substring === '') {
12426 2
            return 0;
12427
        }
12428
12429 13
        if ($encoding === 'UTF-8') {
12430 7
            if ($case_sensitive) {
12431
                return (int) \mb_substr_count($str, $substring);
12432
            }
12433
12434 7
            return (int) \mb_substr_count(
12435 7
                \mb_strtoupper($str),
12436 7
                \mb_strtoupper($substring)
12437
            );
12438
        }
12439
12440 6
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
12441
12442 6
        if ($case_sensitive) {
12443 3
            return (int) \mb_substr_count($str, $substring, $encoding);
12444
        }
12445
12446 3
        return (int) \mb_substr_count(
12447 3
            self::strtocasefold($str, true, false, $encoding, null, false),
12448 3
            self::strtocasefold($substring, true, false, $encoding, null, false),
12449 3
            $encoding
12450
        );
12451
    }
12452
12453
    /**
12454
     * Removes a prefix ($needle) from the beginning of the string ($haystack), case-insensitive.
12455
     *
12456
     * EXMAPLE: <code>
12457
     * UTF8::substr_ileft('ΚόσμεMiddleEnd', 'Κόσμε'); // 'MiddleEnd'
12458
     * UTF8::substr_ileft('ΚόσμεMiddleEnd', 'κόσμε'); // 'MiddleEnd'
12459
     * </code>
12460
     *
12461
     * @param string $haystack <p>The string to search in.</p>
12462
     * @param string $needle   <p>The substring to search for.</p>
12463
     *
12464
     * @psalm-pure
12465
     *
12466
     * @return string
12467
     *                <p>Return the sub-string.</p>
12468
     */
12469
    public static function substr_ileft(string $haystack, string $needle): string
12470
    {
12471 2
        if ($haystack === '') {
12472 2
            return '';
12473
        }
12474
12475 2
        if ($needle === '') {
12476 2
            return $haystack;
12477
        }
12478
12479 2
        if (self::str_istarts_with($haystack, $needle)) {
12480 2
            $haystack = (string) \mb_substr($haystack, (int) self::strlen($needle));
12481
        }
12482
12483 2
        return $haystack;
12484
    }
12485
12486
    /**
12487
     * Get part of a string process in bytes.
12488
     *
12489
     * @param string   $str    <p>The string being checked.</p>
12490
     * @param int      $offset <p>The first position used in str.</p>
12491
     * @param int|null $length [optional] <p>The maximum length of the returned string.</p>
12492
     *
12493
     * @psalm-pure
12494
     *
12495
     * @return false|string
12496
     *                      The portion of <i>str</i> specified by the <i>offset</i> and
12497
     *                      <i>length</i> parameters.</p><p>If <i>str</i> is shorter than <i>offset</i>
12498
     *                      characters long, <b>FALSE</b> will be returned.
12499
     */
12500
    public static function substr_in_byte(string $str, int $offset = 0, int $length = null)
12501
    {
12502
        // empty string
12503 1
        if ($str === '' || $length === 0) {
12504
            return '';
12505
        }
12506
12507
        // whole string
12508 1
        if (!$offset && $length === null) {
12509
            return $str;
12510
        }
12511
12512 1
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
12513
            // "mb_" is available if overload is used, so use it ...
12514
            return \mb_substr($str, $offset, $length, 'CP850'); // 8-BIT
12515
        }
12516
12517 1
        return \substr($str, $offset, $length ?? 2147483647);
12518
    }
12519
12520
    /**
12521
     * Removes a suffix ($needle) from the end of the string ($haystack), case-insensitive.
12522
     *
12523
     * EXAMPLE: <code>
12524
     * UTF8::substr_iright('BeginMiddleΚόσμε', 'Κόσμε'); // 'BeginMiddle'
12525
     * UTF8::substr_iright('BeginMiddleΚόσμε', 'κόσμε'); // 'BeginMiddle'
12526
     * </code>
12527
     *
12528
     * @param string $haystack <p>The string to search in.</p>
12529
     * @param string $needle   <p>The substring to search for.</p>
12530
     *
12531
     * @psalm-pure
12532
     *
12533
     * @return string
12534
     *                <p>Return the sub-string.<p>
12535
     */
12536
    public static function substr_iright(string $haystack, string $needle): string
12537
    {
12538 2
        if ($haystack === '') {
12539 2
            return '';
12540
        }
12541
12542 2
        if ($needle === '') {
12543 2
            return $haystack;
12544
        }
12545
12546 2
        if (self::str_iends_with($haystack, $needle)) {
12547 2
            $haystack = (string) \mb_substr($haystack, 0, (int) self::strlen($haystack) - (int) self::strlen($needle));
12548
        }
12549
12550 2
        return $haystack;
12551
    }
12552
12553
    /**
12554
     * Removes a prefix ($needle) from the beginning of the string ($haystack).
12555
     *
12556
     * EXAMPLE: <code>
12557
     * UTF8::substr_left('ΚόσμεMiddleEnd', 'Κόσμε'); // 'MiddleEnd'
12558
     * UTF8::substr_left('ΚόσμεMiddleEnd', 'κόσμε'); // 'ΚόσμεMiddleEnd'
12559
     * </code>
12560
     *
12561
     * @param string $haystack <p>The string to search in.</p>
12562
     * @param string $needle   <p>The substring to search for.</p>
12563
     *
12564
     * @psalm-pure
12565
     *
12566
     * @return string
12567
     *                <p>Return the sub-string.</p>
12568
     */
12569
    public static function substr_left(string $haystack, string $needle): string
12570
    {
12571 2
        if ($haystack === '') {
12572 2
            return '';
12573
        }
12574
12575 2
        if ($needle === '') {
12576 2
            return $haystack;
12577
        }
12578
12579 2
        if (self::str_starts_with($haystack, $needle)) {
12580 2
            $haystack = (string) \mb_substr($haystack, (int) self::strlen($needle));
12581
        }
12582
12583 2
        return $haystack;
12584
    }
12585
12586
    /**
12587
     * Replace text within a portion of a string.
12588
     *
12589
     * EXAMPLE: <code>UTF8::substr_replace(array('Iñtërnâtiônàlizætiøn', 'foo'), 'æ', 1); // array('Iæñtërnâtiônàlizætiøn', 'fæoo')</code>
12590
     *
12591
     * source: https://gist.github.com/stemar/8287074
12592
     *
12593
     * @param string|string[] $str         <p>The input string or an array of stings.</p>
12594
     * @param string|string[] $replacement <p>The replacement string or an array of stings.</p>
12595
     * @param int|int[]       $offset      <p>
12596
     *                                     If start is positive, the replacing will begin at the start'th offset
12597
     *                                     into string.
12598
     *                                     <br><br>
12599
     *                                     If start is negative, the replacing will begin at the start'th character
12600
     *                                     from the end of string.
12601
     *                                     </p>
12602
     * @param int|int[]|null  $length      [optional] <p>If given and is positive, it represents the length of the
12603
     *                                     portion of string which is to be replaced. If it is negative, it
12604
     *                                     represents the number of characters from the end of string at which to
12605
     *                                     stop replacing. If it is not given, then it will default to strlen(
12606
     *                                     string ); i.e. end the replacing at the end of string. Of course, if
12607
     *                                     length is zero then this function will have the effect of inserting
12608
     *                                     replacement into string at the given start offset.</p>
12609
     * @param string          $encoding    [optional] <p>Set the charset for e.g. "mb_" function</p>
12610
     *
12611
     * @psalm-pure
12612
     *
12613
     * @return string|string[]
12614
     *                         <p>The result string is returned. If string is an array then array is returned.</p>
12615
     */
12616
    public static function substr_replace(
12617
        $str,
12618
        $replacement,
12619
        $offset,
12620
        $length = null,
12621
        string $encoding = 'UTF-8'
12622
    ) {
12623 10
        if (\is_array($str)) {
12624 1
            $num = \count($str);
12625
12626
            // the replacement
12627 1
            if (\is_array($replacement)) {
12628 1
                $replacement = \array_slice($replacement, 0, $num);
12629
            } else {
12630 1
                $replacement = \array_pad([$replacement], $num, $replacement);
12631
            }
12632
12633
            // the offset
12634 1
            if (\is_array($offset)) {
12635 1
                $offset = \array_slice($offset, 0, $num);
12636 1
                foreach ($offset as &$value_tmp) {
12637 1
                    $value_tmp = (int) $value_tmp === $value_tmp ? $value_tmp : 0;
12638
                }
12639 1
                unset($value_tmp);
12640
            } else {
12641 1
                $offset = \array_pad([$offset], $num, $offset);
12642
            }
12643
12644
            // the length
12645 1
            if ($length === null) {
12646 1
                $length = \array_fill(0, $num, 0);
12647 1
            } elseif (\is_array($length)) {
12648 1
                $length = \array_slice($length, 0, $num);
12649 1
                foreach ($length as &$value_tmp_V2) {
12650 1
                    $value_tmp_V2 = (int) $value_tmp_V2 === $value_tmp_V2 ? $value_tmp_V2 : $num;
12651
                }
12652 1
                unset($value_tmp_V2);
12653
            } else {
12654 1
                $length = \array_pad([$length], $num, $length);
12655
            }
12656
12657
            // recursive call
12658 1
            return \array_map([self::class, 'substr_replace'], $str, $replacement, $offset, $length);
12659
        }
12660
12661 10
        if (\is_array($replacement)) {
12662 1
            if ($replacement !== []) {
12663 1
                $replacement = $replacement[0];
12664
            } else {
12665 1
                $replacement = '';
12666
            }
12667
        }
12668
12669
        // init
12670 10
        $str = (string) $str;
12671 10
        $replacement = (string) $replacement;
12672
12673 10
        if (\is_array($length)) {
12674
            throw new \InvalidArgumentException('Parameter "$length" can only be an array, if "$str" is also an array.');
12675
        }
12676
12677 10
        if (\is_array($offset)) {
12678
            throw new \InvalidArgumentException('Parameter "$offset" can only be an array, if "$str" is also an array.');
12679
        }
12680
12681 10
        if ($str === '') {
12682 1
            return $replacement;
12683
        }
12684
12685 9
        if (self::$SUPPORT['mbstring'] === true) {
12686 9
            $string_length = (int) self::strlen($str, $encoding);
12687
12688 9
            if ($offset < 0) {
12689 1
                $offset = (int) \max(0, $string_length + $offset);
12690 9
            } elseif ($offset > $string_length) {
12691 1
                $offset = $string_length;
12692
            }
12693
12694 9
            if ($length !== null && $length < 0) {
12695 1
                $length = (int) \max(0, $string_length - $offset + $length);
12696 9
            } elseif ($length === null || $length > $string_length) {
12697 4
                $length = $string_length;
12698
            }
12699
12700
            /** @noinspection AdditionOperationOnArraysInspection */
12701 9
            if (($offset + $length) > $string_length) {
12702 4
                $length = $string_length - $offset;
12703
            }
12704
12705
            /** @noinspection AdditionOperationOnArraysInspection */
12706 9
            return ((string) \mb_substr($str, 0, $offset, $encoding)) .
12707 9
                   $replacement .
12708 9
                   ((string) \mb_substr($str, $offset + $length, $string_length - $offset - $length, $encoding));
12709
        }
12710
12711
        //
12712
        // fallback for ascii only
12713
        //
12714
12715
        if (ASCII::is_ascii($str)) {
12716
            return ($length === null) ?
12717
                \substr_replace($str, $replacement, $offset) :
12718
                \substr_replace($str, $replacement, $offset, $length);
12719
        }
12720
12721
        //
12722
        // fallback via vanilla php
12723
        //
12724
12725
        \preg_match_all('/./us', $str, $str_matches);
12726
        \preg_match_all('/./us', $replacement, $replacement_matches);
12727
12728
        if ($length === null) {
12729
            $length_tmp = self::strlen($str, $encoding);
12730
            if ($length_tmp === false) {
12731
                // e.g.: non mbstring support + invalid chars
12732
                return '';
12733
            }
12734
            $length = (int) $length_tmp;
12735
        }
12736
12737
        \array_splice($str_matches[0], $offset, $length, $replacement_matches[0]);
12738
12739
        return \implode('', $str_matches[0]);
12740
    }
12741
12742
    /**
12743
     * Removes a suffix ($needle) from the end of the string ($haystack).
12744
     *
12745
     * EXAMPLE: <code>
12746
     * UTF8::substr_right('BeginMiddleΚόσμε', 'Κόσμε'); // 'BeginMiddle'
12747
     * UTF8::substr_right('BeginMiddleΚόσμε', 'κόσμε'); // 'BeginMiddleΚόσμε'
12748
     * </code>
12749
     *
12750
     * @param string $haystack <p>The string to search in.</p>
12751
     * @param string $needle   <p>The substring to search for.</p>
12752
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
12753
     *
12754
     * @psalm-pure
12755
     *
12756
     * @return string
12757
     *                <p>Return the sub-string.</p>
12758
     */
12759
    public static function substr_right(
12760
        string $haystack,
12761
        string $needle,
12762
        string $encoding = 'UTF-8'
12763
    ): string {
12764 2
        if ($haystack === '') {
12765 2
            return '';
12766
        }
12767
12768 2
        if ($needle === '') {
12769 2
            return $haystack;
12770
        }
12771
12772
        if (
12773 2
            $encoding === 'UTF-8'
12774
            &&
12775 2
            \substr($haystack, -\strlen($needle)) === $needle
12776
        ) {
12777 2
            return (string) \mb_substr($haystack, 0, (int) \mb_strlen($haystack) - (int) \mb_strlen($needle));
12778
        }
12779
12780 2
        if (\substr($haystack, -\strlen($needle)) === $needle) {
12781
            return (string) self::substr(
12782
                $haystack,
12783
                0,
12784
                (int) self::strlen($haystack, $encoding) - (int) self::strlen($needle, $encoding),
12785
                $encoding
12786
            );
12787
        }
12788
12789 2
        return $haystack;
12790
    }
12791
12792
    /**
12793
     * Returns a case swapped version of the string.
12794
     *
12795
     * EXAMPLE: <code>UTF8::swapCase('déJÀ σσς iıII'); // 'DÉjà ΣΣΣ IIii'</code>
12796
     *
12797
     * @param string $str        <p>The input string.</p>
12798
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
12799
     * @param bool   $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
12800
     *
12801
     * @psalm-pure
12802
     *
12803
     * @return string
12804
     *                <p>Each character's case swapped.</p>
12805
     */
12806
    public static function swapCase(string $str, string $encoding = 'UTF-8', bool $clean_utf8 = false): string
12807
    {
12808 6
        if ($str === '') {
12809 1
            return '';
12810
        }
12811
12812 6
        if ($clean_utf8) {
12813
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
12814
            // if invalid characters are found in $haystack before $needle
12815 2
            $str = self::clean($str);
12816
        }
12817
12818 6
        if ($encoding === 'UTF-8') {
12819 4
            return (string) (\mb_strtolower($str) ^ \mb_strtoupper($str) ^ $str);
12820
        }
12821
12822 4
        return (string) (self::strtolower($str, $encoding) ^ self::strtoupper($str, $encoding) ^ $str);
12823
    }
12824
12825
    /**
12826
     * Checks whether symfony-polyfills are used.
12827
     *
12828
     * @psalm-pure
12829
     *
12830
     * @return bool
12831
     *              <p><strong>true</strong> if in use, <strong>false</strong> otherwise</p>
12832
     *
12833
     * @internal <p>Please do not use it anymore, we will make is private in next major version.</p>
12834
     */
12835
    public static function symfony_polyfill_used(): bool
12836
    {
12837
        // init
12838
        $return = false;
12839
12840
        $return_tmp = \extension_loaded('mbstring');
12841
        if (!$return_tmp && \function_exists('mb_strlen')) {
12842
            $return = true;
12843
        }
12844
12845
        $return_tmp = \extension_loaded('iconv');
12846
        if (!$return_tmp && \function_exists('iconv')) {
12847
            $return = true;
12848
        }
12849
12850
        return $return;
12851
    }
12852
12853
    /**
12854
     * @param string $str
12855
     * @param int    $tab_length
12856
     *
12857
     * @psalm-pure
12858
     *
12859
     * @return string
12860
     */
12861
    public static function tabs_to_spaces(string $str, int $tab_length = 4): string
12862
    {
12863 6
        if ($tab_length === 4) {
12864 3
            $spaces = '    ';
12865 3
        } elseif ($tab_length === 2) {
12866 1
            $spaces = '  ';
12867
        } else {
12868 2
            $spaces = \str_repeat(' ', $tab_length);
12869
        }
12870
12871 6
        return \str_replace("\t", $spaces, $str);
12872
    }
12873
12874
    /**
12875
     * Converts the first character of each word in the string to uppercase
12876
     * and all other chars to lowercase.
12877
     *
12878
     * @param string      $str                           <p>The input string.</p>
12879
     * @param string      $encoding                      [optional] <p>Set the charset for e.g. "mb_" function</p>
12880
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
12881
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
12882
     *                                                   tr</p>
12883
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ
12884
     *                                                   -> ß</p>
12885
     *
12886
     * @psalm-pure
12887
     *
12888
     * @return string
12889
     *                <p>A string with all characters of $str being title-cased.</p>
12890
     */
12891
    public static function titlecase(
12892
        string $str,
12893
        string $encoding = 'UTF-8',
12894
        bool $clean_utf8 = false,
12895
        string $lang = null,
12896
        bool $try_to_keep_the_string_length = false
12897
    ): string {
12898 5
        if ($clean_utf8) {
12899
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
12900
            // if invalid characters are found in $haystack before $needle
12901
            $str = self::clean($str);
12902
        }
12903
12904
        if (
12905 5
            $lang === null
12906
            &&
12907 5
            !$try_to_keep_the_string_length
12908
        ) {
12909 5
            if ($encoding === 'UTF-8') {
12910 3
                return \mb_convert_case($str, \MB_CASE_TITLE);
12911
            }
12912
12913 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
12914
12915 2
            return \mb_convert_case($str, \MB_CASE_TITLE, $encoding);
12916
        }
12917
12918
        return self::str_titleize(
12919
            $str,
12920
            null,
12921
            $encoding,
12922
            false,
12923
            $lang,
12924
            $try_to_keep_the_string_length,
12925
            false
12926
        );
12927
    }
12928
12929
    /**
12930
     * alias for "UTF8::to_ascii()"
12931
     *
12932
     * @param string $str
12933
     * @param string $subst_chr
12934
     * @param bool   $strict
12935
     *
12936
     * @psalm-pure
12937
     *
12938
     * @return string
12939
     *
12940
     * @see        UTF8::to_ascii()
12941
     * @deprecated <p>please use "UTF8::to_ascii()"</p>
12942
     */
12943
    public static function toAscii(
12944
        string $str,
12945
        string $subst_chr = '?',
12946
        bool $strict = false
12947
    ): string {
12948 7
        return self::to_ascii($str, $subst_chr, $strict);
12949
    }
12950
12951
    /**
12952
     * alias for "UTF8::to_iso8859()"
12953
     *
12954
     * @param string|string[] $str
12955
     *
12956
     * @psalm-pure
12957
     *
12958
     * @return string|string[]
12959
     *
12960
     * @see        UTF8::to_iso8859()
12961
     * @deprecated <p>please use "UTF8::to_iso8859()"</p>
12962
     */
12963
    public static function toIso8859($str)
12964
    {
12965 2
        return self::to_iso8859($str);
12966
    }
12967
12968
    /**
12969
     * alias for "UTF8::to_latin1()"
12970
     *
12971
     * @param string|string[] $str
12972
     *
12973
     * @psalm-pure
12974
     *
12975
     * @return string|string[]
12976
     *
12977
     * @see        UTF8::to_iso8859()
12978
     * @deprecated <p>please use "UTF8::to_iso8859()"</p>
12979
     */
12980
    public static function toLatin1($str)
12981
    {
12982 2
        return self::to_iso8859($str);
12983
    }
12984
12985
    /**
12986
     * alias for "UTF8::to_utf8()"
12987
     *
12988
     * @param string|string[] $str
12989
     *
12990
     * @psalm-pure
12991
     *
12992
     * @return string|string[]
12993
     *
12994
     * @see        UTF8::to_utf8()
12995
     * @deprecated <p>please use "UTF8::to_utf8()"</p>
12996
     */
12997
    public static function toUTF8($str)
12998
    {
12999 2
        return self::to_utf8($str);
13000
    }
13001
13002
    /**
13003
     * Convert a string into ASCII.
13004
     *
13005
     * EXAMPLE: <code>UTF8::to_ascii('déjà σσς iıii'); // 'deja sss iiii'</code>
13006
     *
13007
     * @param string $str     <p>The input string.</p>
13008
     * @param string $unknown [optional] <p>Character use if character unknown. (default is ?)</p>
13009
     * @param bool   $strict  [optional] <p>Use "transliterator_transliterate()" from PHP-Intl | WARNING: bad
13010
     *                        performance</p>
13011
     *
13012
     * @psalm-pure
13013
     *
13014
     * @return string
13015
     */
13016
    public static function to_ascii(
13017
        string $str,
13018
        string $unknown = '?',
13019
        bool $strict = false
13020
    ): string {
13021 37
        return ASCII::to_transliterate($str, $unknown, $strict);
13022
    }
13023
13024
    /**
13025
     * @param bool|int|string $str
13026
     *
13027
     * @phpstan-param bool|int|numeric-string $str
13028
     *
13029
     * @psalm-pure
13030
     *
13031
     * @return bool
13032
     */
13033
    public static function to_boolean($str): bool
13034
    {
13035
        // init
13036 19
        $str = (string) $str;
13037
13038 19
        if ($str === '') {
13039 2
            return false;
13040
        }
13041
13042
        // Info: http://php.net/manual/en/filter.filters.validate.php
13043
        $map = [
13044 17
            'true'  => true,
13045
            '1'     => true,
13046
            'on'    => true,
13047
            'yes'   => true,
13048
            'false' => false,
13049
            '0'     => false,
13050
            'off'   => false,
13051
            'no'    => false,
13052
        ];
13053
13054 17
        if (isset($map[$str])) {
13055 11
            return $map[$str];
13056
        }
13057
13058 6
        $key = \strtolower($str);
13059 6
        if (isset($map[$key])) {
13060 2
            return $map[$key];
13061
        }
13062
13063 4
        if (\is_numeric($str)) {
13064 2
            return ((float) $str + 0) > 0;
13065
        }
13066
13067 2
        return (bool) \trim($str);
13068
    }
13069
13070
    /**
13071
     * Convert given string to safe filename (and keep string case).
13072
     *
13073
     * @param string $str
13074
     * @param bool   $use_transliterate No transliteration, conversion etc. is done by default - unsafe characters are
13075
     *                                  simply replaced with hyphen.
13076
     * @param string $fallback_char
13077
     *
13078
     * @psalm-pure
13079
     *
13080
     * @return string
13081
     */
13082
    public static function to_filename(
13083
        string $str,
13084
        bool $use_transliterate = false,
13085
        string $fallback_char = '-'
13086
    ): string {
13087 1
        return ASCII::to_filename(
13088 1
            $str,
13089 1
            $use_transliterate,
13090 1
            $fallback_char
13091
        );
13092
    }
13093
13094
    /**
13095
     * Convert a string into "ISO-8859"-encoding (Latin-1).
13096
     *
13097
     * EXAMPLE: <code>UTF8::to_utf8(UTF8::to_iso8859('  -ABC-中文空白-  ')); // '  -ABC-????-  '</code>
13098
     *
13099
     * @param string|string[] $str
13100
     *
13101
     * @psalm-pure
13102
     *
13103
     * @return string|string[]
13104
     */
13105
    public static function to_iso8859($str)
13106
    {
13107 8
        if (\is_array($str)) {
13108 2
            foreach ($str as $k => &$v) {
13109 2
                $v = self::to_iso8859($v);
13110
            }
13111
13112 2
            return $str;
13113
        }
13114
13115 8
        $str = (string) $str;
13116 8
        if ($str === '') {
13117 2
            return '';
13118
        }
13119
13120 8
        return self::utf8_decode($str);
13121
    }
13122
13123
    /**
13124
     * alias for "UTF8::to_iso8859()"
13125
     *
13126
     * @param string|string[] $str
13127
     *
13128
     * @psalm-pure
13129
     *
13130
     * @return string|string[]
13131
     *
13132
     * @see        UTF8::to_iso8859()
13133
     * @deprecated <p>please use "UTF8::to_iso8859()"</p>
13134
     */
13135
    public static function to_latin1($str)
13136
    {
13137 2
        return self::to_iso8859($str);
13138
    }
13139
13140
    /**
13141
     * This function leaves UTF-8 characters alone, while converting almost all non-UTF8 to UTF8.
13142
     *
13143
     * <ul>
13144
     * <li>It decode UTF-8 codepoints and Unicode escape sequences.</li>
13145
     * <li>It assumes that the encoding of the original string is either WINDOWS-1252 or ISO-8859.</li>
13146
     * <li>WARNING: It does not remove invalid UTF-8 characters, so you maybe need to use "UTF8::clean()" for this
13147
     * case.</li>
13148
     * </ul>
13149
     *
13150
     * EXAMPLE: <code>UTF8::to_utf8(["\u0063\u0061\u0074"]); // array('cat')</code>
13151
     *
13152
     * @param string|string[] $str                        <p>Any string or array of strings.</p>
13153
     * @param bool            $decode_html_entity_to_utf8 <p>Set to true, if you need to decode html-entities.</p>
13154
     *
13155
     * @psalm-pure
13156
     *
13157
     * @return string|string[]
13158
     *                         <p>The UTF-8 encoded string</p>
13159
     *
13160
     * @template TToUtf8
13161
     * @phpstan-param TToUtf8 $str
13162
     * @phpstan-return TToUtf8
13163
     *
13164
     * @noinspection SuspiciousBinaryOperationInspection
13165
     */
13166
    public static function to_utf8($str, bool $decode_html_entity_to_utf8 = false)
13167
    {
13168 44
        if (\is_array($str)) {
13169 4
            foreach ($str as $k => &$v) {
13170 4
                $v = self::to_utf8_string($v, $decode_html_entity_to_utf8);
13171
            }
13172
13173 4
            return $str;
13174
        }
13175
13176
        /** @phpstan-var TToUtf8 $str */
13177 44
        $str = self::to_utf8_string($str, $decode_html_entity_to_utf8);
13178
13179 44
        return $str;
13180
    }
13181
13182
    /**
13183
     * This function leaves UTF-8 characters alone, while converting almost all non-UTF8 to UTF8.
13184
     *
13185
     * <ul>
13186
     * <li>It decode UTF-8 codepoints and Unicode escape sequences.</li>
13187
     * <li>It assumes that the encoding of the original string is either WINDOWS-1252 or ISO-8859.</li>
13188
     * <li>WARNING: It does not remove invalid UTF-8 characters, so you maybe need to use "UTF8::clean()" for this
13189
     * case.</li>
13190
     * </ul>
13191
     *
13192
     * EXAMPLE: <code>UTF8::to_utf8_string("\u0063\u0061\u0074"); // 'cat'</code>
13193
     *
13194
     * @param string $str                        <p>Any string.</p>
13195
     * @param bool   $decode_html_entity_to_utf8 <p>Set to true, if you need to decode html-entities.</p>
13196
     *
13197
     * @psalm-pure
13198
     *
13199
     * @return string
13200
     *                <p>The UTF-8 encoded string</p>
13201
     *
13202
     * @noinspection SuspiciousBinaryOperationInspection
13203
     */
13204
    public static function to_utf8_string(string $str, bool $decode_html_entity_to_utf8 = false): string
13205
    {
13206 44
        if ($str === '') {
13207 7
            return $str;
13208
        }
13209
13210 44
        $max = \strlen($str);
13211 44
        $buf = '';
13212
13213 44
        for ($i = 0; $i < $max; ++$i) {
13214 44
            $c1 = $str[$i];
13215
13216 44
            if ($c1 >= "\xC0") { // should be converted to UTF8, if it's not UTF8 already
13217
13218 40
                if ($c1 <= "\xDF") { // looks like 2 bytes UTF8
13219
13220 36
                    $c2 = $i + 1 >= $max ? "\x00" : $str[$i + 1];
13221
13222 36
                    if ($c2 >= "\x80" && $c2 <= "\xBF") { // yeah, almost sure it's UTF8 already
13223 22
                        $buf .= $c1 . $c2;
13224 22
                        ++$i;
13225
                    } else { // not valid UTF8 - convert it
13226 36
                        $buf .= self::to_utf8_convert_helper($c1);
13227
                    }
13228 37
                } elseif ($c1 >= "\xE0" && $c1 <= "\xEF") { // looks like 3 bytes UTF8
13229
13230 36
                    $c2 = $i + 1 >= $max ? "\x00" : $str[$i + 1];
13231 36
                    $c3 = $i + 2 >= $max ? "\x00" : $str[$i + 2];
13232
13233 36
                    if ($c2 >= "\x80" && $c2 <= "\xBF" && $c3 >= "\x80" && $c3 <= "\xBF") { // yeah, almost sure it's UTF8 already
13234 17
                        $buf .= $c1 . $c2 . $c3;
13235 17
                        $i += 2;
13236
                    } else { // not valid UTF8 - convert it
13237 36
                        $buf .= self::to_utf8_convert_helper($c1);
13238
                    }
13239 28
                } elseif ($c1 >= "\xF0" && $c1 <= "\xF7") { // looks like 4 bytes UTF8
13240
13241 28
                    $c2 = $i + 1 >= $max ? "\x00" : $str[$i + 1];
13242 28
                    $c3 = $i + 2 >= $max ? "\x00" : $str[$i + 2];
13243 28
                    $c4 = $i + 3 >= $max ? "\x00" : $str[$i + 3];
13244
13245 28
                    if ($c2 >= "\x80" && $c2 <= "\xBF" && $c3 >= "\x80" && $c3 <= "\xBF" && $c4 >= "\x80" && $c4 <= "\xBF") { // yeah, almost sure it's UTF8 already
13246 10
                        $buf .= $c1 . $c2 . $c3 . $c4;
13247 10
                        $i += 3;
13248
                    } else { // not valid UTF8 - convert it
13249 28
                        $buf .= self::to_utf8_convert_helper($c1);
13250
                    }
13251
                } else { // doesn't look like UTF8, but should be converted
13252
13253 40
                    $buf .= self::to_utf8_convert_helper($c1);
13254
                }
13255 41
            } elseif (($c1 & "\xC0") === "\x80") { // needs conversion
13256
13257 4
                $buf .= self::to_utf8_convert_helper($c1);
13258
            } else { // it doesn't need conversion
13259
13260 41
                $buf .= $c1;
13261
            }
13262
        }
13263
13264
        // decode unicode escape sequences + unicode surrogate pairs
13265 44
        $buf = \preg_replace_callback(
13266 44
            '/\\\\u([dD][89abAB][0-9a-fA-F]{2})\\\\u([dD][cdefCDEF][\da-fA-F]{2})|\\\\u([0-9a-fA-F]{4})/',
13267
            /**
13268
             * @param array $matches
13269
             *
13270
             * @psalm-pure
13271
             *
13272
             * @return string
13273
             */
13274
            static function (array $matches): string {
13275 13
                if (isset($matches[3])) {
13276 13
                    $cp = (int) \hexdec($matches[3]);
13277
                } else {
13278
                    // http://unicode.org/faq/utf_bom.html#utf16-4
13279 1
                    $cp = ((int) \hexdec($matches[1]) << 10)
13280 1
                          + (int) \hexdec($matches[2])
13281 1
                          + 0x10000
13282 1
                          - (0xD800 << 10)
13283 1
                          - 0xDC00;
13284
                }
13285
13286
                // https://github.com/php/php-src/blob/php-7.3.2/ext/standard/html.c#L471
13287
                //
13288
                // php_utf32_utf8(unsigned char *buf, unsigned k)
13289
13290 13
                if ($cp < 0x80) {
13291 8
                    return (string) self::chr($cp);
13292
                }
13293
13294 10
                if ($cp < 0xA0) {
13295
                    /** @noinspection UnnecessaryCastingInspection */
13296
                    return (string) self::chr(0xC0 | $cp >> 6) . (string) self::chr(0x80 | $cp & 0x3F);
13297
                }
13298
13299 10
                return self::decimal_to_chr($cp);
13300 44
            },
13301 44
            $buf
13302
        );
13303
13304 44
        if ($buf === null) {
13305
            return '';
13306
        }
13307
13308
        // decode UTF-8 codepoints
13309 44
        if ($decode_html_entity_to_utf8) {
13310 3
            $buf = self::html_entity_decode($buf);
13311
        }
13312
13313 44
        return $buf;
13314
    }
13315
13316
    /**
13317
     * Returns the given string as an integer, or null if the string isn't numeric.
13318
     *
13319
     * @param string $str
13320
     *
13321
     * @psalm-pure
13322
     *
13323
     * @return int|null
13324
     *                  <p>null if the string isn't numeric</p>
13325
     */
13326
    public static function to_int(string $str)
13327
    {
13328 1
        if (\is_numeric($str)) {
13329 1
            return (int) $str;
13330
        }
13331
13332 1
        return null;
13333
    }
13334
13335
    /**
13336
     * Returns the given input as string, or null if the input isn't int|float|string
13337
     * and do not implement the "__toString()" method.
13338
     *
13339
     * @param float|int|object|string|null $input
13340
     *
13341
     * @psalm-pure
13342
     *
13343
     * @return string|null
13344
     *                     <p>null if the input isn't int|float|string and has no "__toString()" method</p>
13345
     */
13346
    public static function to_string($input)
13347
    {
13348 1
        if ($input === null) {
13349
            return null;
13350
        }
13351
13352
        /** @var string $input_type - hack for psalm */
13353 1
        $input_type = \gettype($input);
13354
13355
        if (
13356 1
            $input_type === 'string'
13357
            ||
13358 1
            $input_type === 'integer'
13359
            ||
13360 1
            $input_type === 'float'
13361
            ||
13362 1
            $input_type === 'double'
13363
        ) {
13364 1
            return (string) $input;
13365
        }
13366
13367 1
        if ($input_type === 'object') {
13368
            /** @noinspection PhpSillyAssignmentInspection */
13369
            /** @var object $input - hack for psalm / phpstan */
13370 1
            $input = $input;
13371
            /** @noinspection NestedPositiveIfStatementsInspection */
13372
            /** @noinspection MissingOrEmptyGroupStatementInspection */
13373 1
            if (\method_exists($input, '__toString')) {
13374 1
                return (string) $input;
13375
            }
13376
        }
13377
13378 1
        return null;
13379
    }
13380
13381
    /**
13382
     * Strip whitespace or other characters from the beginning and end of a UTF-8 string.
13383
     *
13384
     * INFO: This is slower then "trim()"
13385
     *
13386
     * We can only use the original-function, if we use <= 7-Bit in the string / chars
13387
     * but the check for ASCII (7-Bit) cost more time, then we can safe here.
13388
     *
13389
     * EXAMPLE: <code>UTF8::trim('   -ABC-中文空白-  '); // '-ABC-中文空白-'</code>
13390
     *
13391
     * @param string      $str   <p>The string to be trimmed</p>
13392
     * @param string|null $chars [optional] <p>Optional characters to be stripped</p>
13393
     *
13394
     * @psalm-pure
13395
     *
13396
     * @return string
13397
     *                <p>The trimmed string.</p>
13398
     */
13399
    public static function trim(string $str = '', string $chars = null): string
13400
    {
13401 57
        if ($str === '') {
13402 9
            return '';
13403
        }
13404
13405 50
        if (self::$SUPPORT['mbstring'] === true) {
13406 50
            if ($chars !== null) {
13407
                /** @noinspection PregQuoteUsageInspection */
13408 28
                $chars = \preg_quote($chars);
13409 28
                $pattern = "^[${chars}]+|[${chars}]+\$";
13410
            } else {
13411 22
                $pattern = '^[\\s]+|[\\s]+$';
13412
            }
13413
13414
            /** @noinspection PhpComposerExtensionStubsInspection */
13415 50
            return (string) \mb_ereg_replace($pattern, '', $str);
13416
        }
13417
13418 8
        if ($chars !== null) {
13419
            $chars = \preg_quote($chars, '/');
13420
            $pattern = "^[${chars}]+|[${chars}]+\$";
13421
        } else {
13422 8
            $pattern = '^[\\s]+|[\\s]+$';
13423
        }
13424
13425 8
        return self::regex_replace($str, $pattern, '');
13426
    }
13427
13428
    /**
13429
     * Makes string's first char uppercase.
13430
     *
13431
     * EXAMPLE: <code>UTF8::ucfirst('ñtërnâtiônàlizætiøn foo'); // 'Ñtërnâtiônàlizætiøn foo'</code>
13432
     *
13433
     * @param string      $str                           <p>The input string.</p>
13434
     * @param string      $encoding                      [optional] <p>Set the charset for e.g. "mb_" function</p>
13435
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
13436
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
13437
     *                                                   tr</p>
13438
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ
13439
     *                                                   -> ß</p>
13440
     *
13441
     * @psalm-pure
13442
     *
13443
     * @return string
13444
     *                <p>The resulting string with with char uppercase.</p>
13445
     */
13446
    public static function ucfirst(
13447
        string $str,
13448
        string $encoding = 'UTF-8',
13449
        bool $clean_utf8 = false,
13450
        string $lang = null,
13451
        bool $try_to_keep_the_string_length = false
13452
    ): string {
13453 69
        if ($str === '') {
13454 3
            return '';
13455
        }
13456
13457 68
        if ($clean_utf8) {
13458
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
13459
            // if invalid characters are found in $haystack before $needle
13460 1
            $str = self::clean($str);
13461
        }
13462
13463 68
        $use_mb_functions = $lang === null && !$try_to_keep_the_string_length;
13464
13465 68
        if ($encoding === 'UTF-8') {
13466 22
            $str_part_two = (string) \mb_substr($str, 1);
13467
13468 22
            if ($use_mb_functions) {
13469 22
                $str_part_one = \mb_strtoupper(
13470 22
                    (string) \mb_substr($str, 0, 1)
13471
                );
13472
            } else {
13473
                $str_part_one = self::strtoupper(
13474
                    (string) \mb_substr($str, 0, 1),
13475
                    $encoding,
13476
                    false,
13477
                    $lang,
13478 22
                    $try_to_keep_the_string_length
13479
                );
13480
            }
13481
        } else {
13482 47
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
13483
13484 47
            $str_part_two = (string) self::substr($str, 1, null, $encoding);
13485
13486 47
            if ($use_mb_functions) {
13487 47
                $str_part_one = \mb_strtoupper(
13488 47
                    (string) \mb_substr($str, 0, 1, $encoding),
13489 47
                    $encoding
13490
                );
13491
            } else {
13492
                $str_part_one = self::strtoupper(
13493
                    (string) self::substr($str, 0, 1, $encoding),
13494
                    $encoding,
13495
                    false,
13496
                    $lang,
13497
                    $try_to_keep_the_string_length
13498
                );
13499
            }
13500
        }
13501
13502 68
        return $str_part_one . $str_part_two;
13503
    }
13504
13505
    /**
13506
     * alias for "UTF8::ucfirst()"
13507
     *
13508
     * @param string $str
13509
     * @param string $encoding
13510
     * @param bool   $clean_utf8
13511
     *
13512
     * @psalm-pure
13513
     *
13514
     * @return string
13515
     *
13516
     * @see        UTF8::ucfirst()
13517
     * @deprecated <p>please use "UTF8::ucfirst()"</p>
13518
     */
13519
    public static function ucword(
13520
        string $str,
13521
        string $encoding = 'UTF-8',
13522
        bool $clean_utf8 = false
13523
    ): string {
13524 1
        return self::ucfirst($str, $encoding, $clean_utf8);
13525
    }
13526
13527
    /**
13528
     * Uppercase for all words in the string.
13529
     *
13530
     * EXAMPLE: <code>UTF8::ucwords('iñt ërn âTi ônà liz æti øn'); // 'Iñt Ërn ÂTi Ônà Liz Æti Øn'</code>
13531
     *
13532
     * @param string   $str        <p>The input string.</p>
13533
     * @param string[] $exceptions [optional] <p>Exclusion for some words.</p>
13534
     * @param string   $char_list  [optional] <p>Additional chars that contains to words and do not start a new
13535
     *                             word.</p>
13536
     * @param string   $encoding   [optional] <p>Set the charset.</p>
13537
     * @param bool     $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
13538
     *
13539
     * @psalm-pure
13540
     *
13541
     * @return string
13542
     */
13543
    public static function ucwords(
13544
        string $str,
13545
        array $exceptions = [],
13546
        string $char_list = '',
13547
        string $encoding = 'UTF-8',
13548
        bool $clean_utf8 = false
13549
    ): string {
13550 8
        if (!$str) {
13551 2
            return '';
13552
        }
13553
13554
        // INFO: mb_convert_case($str, MB_CASE_TITLE);
13555
        // -> MB_CASE_TITLE didn't only uppercase the first letter, it also lowercase all other letters
13556
13557 7
        if ($clean_utf8) {
13558
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
13559
            // if invalid characters are found in $haystack before $needle
13560 1
            $str = self::clean($str);
13561
        }
13562
13563 7
        $use_php_default_functions = !(bool) ($char_list . \implode('', $exceptions));
13564
13565
        if (
13566 7
            $use_php_default_functions
13567
            &&
13568 7
            ASCII::is_ascii($str)
13569
        ) {
13570
            return \ucwords($str);
13571
        }
13572
13573 7
        $words = self::str_to_words($str, $char_list);
13574 7
        $use_exceptions = $exceptions !== [];
13575
13576 7
        $words_str = '';
13577 7
        foreach ($words as &$word) {
13578 7
            if (!$word) {
13579 7
                continue;
13580
            }
13581
13582
            if (
13583 7
                !$use_exceptions
13584
                ||
13585 7
                !\in_array($word, $exceptions, true)
13586
            ) {
13587 7
                $words_str .= self::ucfirst($word, $encoding);
13588
            } else {
13589 7
                $words_str .= $word;
13590
            }
13591
        }
13592
13593 7
        return $words_str;
13594
    }
13595
13596
    /**
13597
     * Multi decode HTML entity + fix urlencoded-win1252-chars.
13598
     *
13599
     * EXAMPLE: <code>UTF8::urldecode('tes%20öäü%20\u00edtest+test'); // 'tes öäü ítest test'</code>
13600
     *
13601
     * e.g:
13602
     * 'test+test'                     => 'test test'
13603
     * 'D&#252;sseldorf'               => 'Düsseldorf'
13604
     * 'D%FCsseldorf'                  => 'Düsseldorf'
13605
     * 'D&#xFC;sseldorf'               => 'Düsseldorf'
13606
     * 'D%26%23xFC%3Bsseldorf'         => 'Düsseldorf'
13607
     * 'Düsseldorf'                   => 'Düsseldorf'
13608
     * 'D%C3%BCsseldorf'               => 'Düsseldorf'
13609
     * 'D%C3%83%C2%BCsseldorf'         => 'Düsseldorf'
13610
     * 'D%25C3%2583%25C2%25BCsseldorf' => 'Düsseldorf'
13611
     *
13612
     * @param string $str          <p>The input string.</p>
13613
     * @param bool   $multi_decode <p>Decode as often as possible.</p>
13614
     *
13615
     * @psalm-pure
13616
     *
13617
     * @return string
13618
     */
13619
    public static function urldecode(string $str, bool $multi_decode = true): string
13620
    {
13621 4
        if ($str === '') {
13622 3
            return '';
13623
        }
13624
13625
        if (
13626 4
            \strpos($str, '&') === false
13627
            &&
13628 4
            \strpos($str, '%') === false
13629
            &&
13630 4
            \strpos($str, '+') === false
13631
            &&
13632 4
            \strpos($str, '\u') === false
13633
        ) {
13634 3
            return self::fix_simple_utf8($str);
13635
        }
13636
13637 4
        $str = self::urldecode_unicode_helper($str);
13638
13639 4
        if ($multi_decode) {
13640
            do {
13641 3
                $str_compare = $str;
13642
13643
                /**
13644
                 * @psalm-suppress PossiblyInvalidArgument
13645
                 */
13646 3
                $str = self::fix_simple_utf8(
13647 3
                    \urldecode(
13648 3
                        self::html_entity_decode(
13649 3
                            self::to_utf8($str),
13650 3
                            \ENT_QUOTES | \ENT_HTML5
13651
                        )
13652
                    )
13653
                );
13654 3
            } while ($str_compare !== $str);
13655
        } else {
13656
            /**
13657
             * @psalm-suppress PossiblyInvalidArgument
13658
             */
13659 1
            $str = self::fix_simple_utf8(
13660 1
                \urldecode(
13661 1
                    self::html_entity_decode(
13662 1
                        self::to_utf8($str),
13663 1
                        \ENT_QUOTES | \ENT_HTML5
13664
                    )
13665
                )
13666
            );
13667
        }
13668
13669 4
        return $str;
13670
    }
13671
13672
    /**
13673
     * Return a array with "urlencoded"-win1252 -> UTF-8
13674
     *
13675
     * @psalm-pure
13676
     *
13677
     * @return string[]
13678
     *
13679
     * @deprecated <p>please use the "UTF8::urldecode()" function to decode a string</p>
13680
     */
13681
    public static function urldecode_fix_win1252_chars(): array
13682
    {
13683
        return [
13684 2
            '%20' => ' ',
13685
            '%21' => '!',
13686
            '%22' => '"',
13687
            '%23' => '#',
13688
            '%24' => '$',
13689
            '%25' => '%',
13690
            '%26' => '&',
13691
            '%27' => "'",
13692
            '%28' => '(',
13693
            '%29' => ')',
13694
            '%2A' => '*',
13695
            '%2B' => '+',
13696
            '%2C' => ',',
13697
            '%2D' => '-',
13698
            '%2E' => '.',
13699
            '%2F' => '/',
13700
            '%30' => '0',
13701
            '%31' => '1',
13702
            '%32' => '2',
13703
            '%33' => '3',
13704
            '%34' => '4',
13705
            '%35' => '5',
13706
            '%36' => '6',
13707
            '%37' => '7',
13708
            '%38' => '8',
13709
            '%39' => '9',
13710
            '%3A' => ':',
13711
            '%3B' => ';',
13712
            '%3C' => '<',
13713
            '%3D' => '=',
13714
            '%3E' => '>',
13715
            '%3F' => '?',
13716
            '%40' => '@',
13717
            '%41' => 'A',
13718
            '%42' => 'B',
13719
            '%43' => 'C',
13720
            '%44' => 'D',
13721
            '%45' => 'E',
13722
            '%46' => 'F',
13723
            '%47' => 'G',
13724
            '%48' => 'H',
13725
            '%49' => 'I',
13726
            '%4A' => 'J',
13727
            '%4B' => 'K',
13728
            '%4C' => 'L',
13729
            '%4D' => 'M',
13730
            '%4E' => 'N',
13731
            '%4F' => 'O',
13732
            '%50' => 'P',
13733
            '%51' => 'Q',
13734
            '%52' => 'R',
13735
            '%53' => 'S',
13736
            '%54' => 'T',
13737
            '%55' => 'U',
13738
            '%56' => 'V',
13739
            '%57' => 'W',
13740
            '%58' => 'X',
13741
            '%59' => 'Y',
13742
            '%5A' => 'Z',
13743
            '%5B' => '[',
13744
            '%5C' => '\\',
13745
            '%5D' => ']',
13746
            '%5E' => '^',
13747
            '%5F' => '_',
13748
            '%60' => '`',
13749
            '%61' => 'a',
13750
            '%62' => 'b',
13751
            '%63' => 'c',
13752
            '%64' => 'd',
13753
            '%65' => 'e',
13754
            '%66' => 'f',
13755
            '%67' => 'g',
13756
            '%68' => 'h',
13757
            '%69' => 'i',
13758
            '%6A' => 'j',
13759
            '%6B' => 'k',
13760
            '%6C' => 'l',
13761
            '%6D' => 'm',
13762
            '%6E' => 'n',
13763
            '%6F' => 'o',
13764
            '%70' => 'p',
13765
            '%71' => 'q',
13766
            '%72' => 'r',
13767
            '%73' => 's',
13768
            '%74' => 't',
13769
            '%75' => 'u',
13770
            '%76' => 'v',
13771
            '%77' => 'w',
13772
            '%78' => 'x',
13773
            '%79' => 'y',
13774
            '%7A' => 'z',
13775
            '%7B' => '{',
13776
            '%7C' => '|',
13777
            '%7D' => '}',
13778
            '%7E' => '~',
13779
            '%7F' => '',
13780
            '%80' => '`',
13781
            '%81' => '',
13782
            '%82' => '‚',
13783
            '%83' => 'ƒ',
13784
            '%84' => '„',
13785
            '%85' => '…',
13786
            '%86' => '†',
13787
            '%87' => '‡',
13788
            '%88' => 'ˆ',
13789
            '%89' => '‰',
13790
            '%8A' => 'Š',
13791
            '%8B' => '‹',
13792
            '%8C' => 'Œ',
13793
            '%8D' => '',
13794
            '%8E' => 'Ž',
13795
            '%8F' => '',
13796
            '%90' => '',
13797
            '%91' => '‘',
13798
            '%92' => '’',
13799
            '%93' => '“',
13800
            '%94' => '”',
13801
            '%95' => '•',
13802
            '%96' => '–',
13803
            '%97' => '—',
13804
            '%98' => '˜',
13805
            '%99' => '™',
13806
            '%9A' => 'š',
13807
            '%9B' => '›',
13808
            '%9C' => 'œ',
13809
            '%9D' => '',
13810
            '%9E' => 'ž',
13811
            '%9F' => 'Ÿ',
13812
            '%A0' => '',
13813
            '%A1' => '¡',
13814
            '%A2' => '¢',
13815
            '%A3' => '£',
13816
            '%A4' => '¤',
13817
            '%A5' => '¥',
13818
            '%A6' => '¦',
13819
            '%A7' => '§',
13820
            '%A8' => '¨',
13821
            '%A9' => '©',
13822
            '%AA' => 'ª',
13823
            '%AB' => '«',
13824
            '%AC' => '¬',
13825
            '%AD' => '',
13826
            '%AE' => '®',
13827
            '%AF' => '¯',
13828
            '%B0' => '°',
13829
            '%B1' => '±',
13830
            '%B2' => '²',
13831
            '%B3' => '³',
13832
            '%B4' => '´',
13833
            '%B5' => 'µ',
13834
            '%B6' => '¶',
13835
            '%B7' => '·',
13836
            '%B8' => '¸',
13837
            '%B9' => '¹',
13838
            '%BA' => 'º',
13839
            '%BB' => '»',
13840
            '%BC' => '¼',
13841
            '%BD' => '½',
13842
            '%BE' => '¾',
13843
            '%BF' => '¿',
13844
            '%C0' => 'À',
13845
            '%C1' => 'Á',
13846
            '%C2' => 'Â',
13847
            '%C3' => 'Ã',
13848
            '%C4' => 'Ä',
13849
            '%C5' => 'Å',
13850
            '%C6' => 'Æ',
13851
            '%C7' => 'Ç',
13852
            '%C8' => 'È',
13853
            '%C9' => 'É',
13854
            '%CA' => 'Ê',
13855
            '%CB' => 'Ë',
13856
            '%CC' => 'Ì',
13857
            '%CD' => 'Í',
13858
            '%CE' => 'Î',
13859
            '%CF' => 'Ï',
13860
            '%D0' => 'Ð',
13861
            '%D1' => 'Ñ',
13862
            '%D2' => 'Ò',
13863
            '%D3' => 'Ó',
13864
            '%D4' => 'Ô',
13865
            '%D5' => 'Õ',
13866
            '%D6' => 'Ö',
13867
            '%D7' => '×',
13868
            '%D8' => 'Ø',
13869
            '%D9' => 'Ù',
13870
            '%DA' => 'Ú',
13871
            '%DB' => 'Û',
13872
            '%DC' => 'Ü',
13873
            '%DD' => 'Ý',
13874
            '%DE' => 'Þ',
13875
            '%DF' => 'ß',
13876
            '%E0' => 'à',
13877
            '%E1' => 'á',
13878
            '%E2' => 'â',
13879
            '%E3' => 'ã',
13880
            '%E4' => 'ä',
13881
            '%E5' => 'å',
13882
            '%E6' => 'æ',
13883
            '%E7' => 'ç',
13884
            '%E8' => 'è',
13885
            '%E9' => 'é',
13886
            '%EA' => 'ê',
13887
            '%EB' => 'ë',
13888
            '%EC' => 'ì',
13889
            '%ED' => 'í',
13890
            '%EE' => 'î',
13891
            '%EF' => 'ï',
13892
            '%F0' => 'ð',
13893
            '%F1' => 'ñ',
13894
            '%F2' => 'ò',
13895
            '%F3' => 'ó',
13896
            '%F4' => 'ô',
13897
            '%F5' => 'õ',
13898
            '%F6' => 'ö',
13899
            '%F7' => '÷',
13900
            '%F8' => 'ø',
13901
            '%F9' => 'ù',
13902
            '%FA' => 'ú',
13903
            '%FB' => 'û',
13904
            '%FC' => 'ü',
13905
            '%FD' => 'ý',
13906
            '%FE' => 'þ',
13907
            '%FF' => 'ÿ',
13908
        ];
13909
    }
13910
13911
    /**
13912
     * Decodes a UTF-8 string to ISO-8859-1.
13913
     *
13914
     * EXAMPLE: <code>UTF8::encode('UTF-8', UTF8::utf8_decode('-ABC-中文空白-')); // '-ABC-????-'</code>
13915
     *
13916
     * @param string $str             <p>The input string.</p>
13917
     * @param bool   $keep_utf8_chars
13918
     *
13919
     * @psalm-pure
13920
     *
13921
     * @return string
13922
     *
13923
     * @noinspection SuspiciousBinaryOperationInspection
13924
     */
13925
    public static function utf8_decode(string $str, bool $keep_utf8_chars = false): string
13926
    {
13927 14
        if ($str === '') {
13928 6
            return '';
13929
        }
13930
13931
        // save for later comparision
13932 14
        $str_backup = $str;
13933 14
        $len = \strlen($str);
13934
13935 14
        if (self::$ORD === null) {
13936
            self::$ORD = self::getData('ord');
13937
        }
13938
13939 14
        if (self::$CHR === null) {
13940
            self::$CHR = self::getData('chr');
13941
        }
13942
13943 14
        $no_char_found = '?';
13944
        /** @noinspection ForeachInvariantsInspection */
13945 14
        for ($i = 0, $j = 0; $i < $len; ++$i, ++$j) {
13946 14
            switch ($str[$i] & "\xF0") {
13947 14
                case "\xC0":
13948 13
                case "\xD0":
13949 13
                    $c = (self::$ORD[$str[$i] & "\x1F"] << 6) | self::$ORD[$str[++$i] & "\x3F"];
13950 13
                    $str[$j] = $c < 256 ? self::$CHR[$c] : $no_char_found;
13951
13952 13
                    break;
13953
13954
                /** @noinspection PhpMissingBreakStatementInspection */
13955 13
                case "\xF0":
13956
                    ++$i;
13957
13958
                // no break
13959
13960 13
                case "\xE0":
13961 11
                    $str[$j] = $no_char_found;
13962 11
                    $i += 2;
13963
13964 11
                    break;
13965
13966
                default:
13967 12
                    $str[$j] = $str[$i];
13968
            }
13969
        }
13970
13971
        /** @var false|string $return - needed for PhpStan (stubs error) */
13972 14
        $return = \substr($str, 0, $j);
13973 14
        if ($return === false) {
13974
            $return = '';
13975
        }
13976
13977
        if (
13978 14
            $keep_utf8_chars
13979
            &&
13980 14
            (int) self::strlen($return) >= (int) self::strlen($str_backup)
13981
        ) {
13982 2
            return $str_backup;
13983
        }
13984
13985 14
        return $return;
13986
    }
13987
13988
    /**
13989
     * Encodes an ISO-8859-1 string to UTF-8.
13990
     *
13991
     * EXAMPLE: <code>UTF8::utf8_decode(UTF8::utf8_encode('-ABC-中文空白-')); // '-ABC-中文空白-'</code>
13992
     *
13993
     * @param string $str <p>The input string.</p>
13994
     *
13995
     * @psalm-pure
13996
     *
13997
     * @return string
13998
     */
13999
    public static function utf8_encode(string $str): string
14000
    {
14001 16
        if ($str === '') {
14002 14
            return '';
14003
        }
14004
14005
        /** @var false|string $str - the polyfill maybe return false */
14006 16
        $str = \utf8_encode($str);
0 ignored issues
show
Bug introduced by
It seems like $str can also be of type false; however, parameter $data of utf8_encode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

14006
        $str = \utf8_encode(/** @scrutinizer ignore-type */ $str);
Loading history...
14007
14008
        /** @noinspection CallableParameterUseCaseInTypeContextInspection */
14009
        /** @psalm-suppress TypeDoesNotContainType */
14010 16
        if ($str === false) {
14011
            return '';
14012
        }
14013
14014 16
        return $str;
14015
    }
14016
14017
    /**
14018
     * fix -> utf8-win1252 chars
14019
     *
14020
     * @param string $str <p>The input string.</p>
14021
     *
14022
     * @psalm-pure
14023
     *
14024
     * @return string
14025
     *
14026
     * @deprecated <p>please use "UTF8::fix_simple_utf8()"</p>
14027
     */
14028
    public static function utf8_fix_win1252_chars(string $str): string
14029
    {
14030 2
        return self::fix_simple_utf8($str);
14031
    }
14032
14033
    /**
14034
     * Returns an array with all utf8 whitespace characters.
14035
     *
14036
     * @see http://www.bogofilter.org/pipermail/bogofilter/2003-March/001889.html
14037
     *
14038
     * @psalm-pure
14039
     *
14040
     * @return string[]
14041
     *                  An array with all known whitespace characters as values and the type of whitespace as keys
14042
     *                  as defined in above URL
14043
     */
14044
    public static function whitespace_table(): array
14045
    {
14046 2
        return self::$WHITESPACE_TABLE;
14047
    }
14048
14049
    /**
14050
     * Limit the number of words in a string.
14051
     *
14052
     * EXAMPLE: <code>UTF8::words_limit('fòô bàř fòô', 2, ''); // 'fòô bàř'</code>
14053
     *
14054
     * @param string $str        <p>The input string.</p>
14055
     * @param int    $limit      <p>The limit of words as integer.</p>
14056
     * @param string $str_add_on <p>Replacement for the striped string.</p>
14057
     *
14058
     * @psalm-pure
14059
     *
14060
     * @return string
14061
     */
14062
    public static function words_limit(
14063
        string $str,
14064
        int $limit = 100,
14065
        string $str_add_on = '…'
14066
    ): string {
14067 2
        if ($str === '' || $limit < 1) {
14068 2
            return '';
14069
        }
14070
14071 2
        \preg_match('/^\\s*+(?:[^\\s]++\\s*+){1,' . $limit . '}/u', $str, $matches);
14072
14073
        if (
14074 2
            !isset($matches[0])
14075
            ||
14076 2
            \mb_strlen($str) === (int) \mb_strlen($matches[0])
14077
        ) {
14078 2
            return $str;
14079
        }
14080
14081 2
        return \rtrim($matches[0]) . $str_add_on;
14082
    }
14083
14084
    /**
14085
     * Wraps a string to a given number of characters
14086
     *
14087
     * EXAMPLE: <code>UTF8::wordwrap('Iñtërnâtiônàlizætiøn', 2, '<br>', true)); // 'Iñ<br>të<br>rn<br>ât<br>iô<br>nà<br>li<br>zæ<br>ti<br>øn'</code>
14088
     *
14089
     * @see http://php.net/manual/en/function.wordwrap.php
14090
     *
14091
     * @param string $str   <p>The input string.</p>
14092
     * @param int    $width [optional] <p>The column width.</p>
14093
     * @param string $break [optional] <p>The line is broken using the optional break parameter.</p>
14094
     * @param bool   $cut   [optional] <p>
14095
     *                      If the cut is set to true, the string is
14096
     *                      always wrapped at or before the specified width. So if you have
14097
     *                      a word that is larger than the given width, it is broken apart.
14098
     *                      </p>
14099
     *
14100
     * @psalm-pure
14101
     *
14102
     * @return string
14103
     *                <p>The given string wrapped at the specified column.</p>
14104
     */
14105
    public static function wordwrap(
14106
        string $str,
14107
        int $width = 75,
14108
        string $break = "\n",
14109
        bool $cut = false
14110
    ): string {
14111 12
        if ($str === '' || $break === '') {
14112 4
            return '';
14113
        }
14114
14115 10
        $str_split = \explode($break, $str);
14116 10
        if ($str_split === false) {
14117
            return '';
14118
        }
14119
14120
        /** @var string[] $charsArray */
14121 10
        $charsArray = [];
14122 10
        $word_split = '';
14123 10
        foreach ($str_split as $i => $i_value) {
14124 10
            if ($i) {
14125 3
                $charsArray[] = $break;
14126 3
                $word_split .= '#';
14127
            }
14128
14129 10
            foreach (self::str_split($i_value) as $c) {
14130 10
                $charsArray[] = $c;
14131 10
                if ($c === ' ') {
14132 3
                    $word_split .= ' ';
14133
                } else {
14134 10
                    $word_split .= '?';
14135
                }
14136
            }
14137
        }
14138
14139 10
        $str_return = '';
14140 10
        $j = 0;
14141 10
        $b = -1;
14142 10
        $i = -1;
14143 10
        $word_split = \wordwrap($word_split, $width, '#', $cut);
14144
14145 10
        $max = \mb_strlen($word_split);
14146 10
        while (($b = \mb_strpos($word_split, '#', $b + 1)) !== false) {
14147 8
            for (++$i; $i < $b; ++$i) {
14148 8
                if (isset($charsArray[$j])) {
14149 8
                    $str_return .= $charsArray[$j];
14150 8
                    unset($charsArray[$j]);
14151
                }
14152 8
                ++$j;
14153
14154
                // prevent endless loop, e.g. if there is a error in the "mb_*" polyfill
14155 8
                if ($i > $max) {
14156
                    break 2;
14157
                }
14158
            }
14159
14160
            if (
14161 8
                $break === $charsArray[$j]
14162
                ||
14163 8
                $charsArray[$j] === ' '
14164
            ) {
14165 5
                unset($charsArray[$j++]);
14166
            }
14167
14168 8
            $str_return .= $break;
14169
14170
            // prevent endless loop, e.g. if there is a error in the "mb_*" polyfill
14171 8
            if ($b > $max) {
14172
                break;
14173
            }
14174
        }
14175
14176 10
        return $str_return . \implode('', $charsArray);
14177
    }
14178
14179
    /**
14180
     * Line-Wrap the string after $limit, but split the string by "$delimiter" before ...
14181
     *    ... so that we wrap the per line.
14182
     *
14183
     * @param string      $str             <p>The input string.</p>
14184
     * @param int         $width           [optional] <p>The column width.</p>
14185
     * @param string      $break           [optional] <p>The line is broken using the optional break parameter.</p>
14186
     * @param bool        $cut             [optional] <p>
14187
     *                                     If the cut is set to true, the string is
14188
     *                                     always wrapped at or before the specified width. So if you have
14189
     *                                     a word that is larger than the given width, it is broken apart.
14190
     *                                     </p>
14191
     * @param bool        $add_final_break [optional] <p>
14192
     *                                     If this flag is true, then the method will add a $break at the end
14193
     *                                     of the result string.
14194
     *                                     </p>
14195
     * @param string|null $delimiter       [optional] <p>
14196
     *                                     You can change the default behavior, where we split the string by newline.
14197
     *                                     </p>
14198
     *
14199
     * @psalm-pure
14200
     *
14201
     * @return string
14202
     */
14203
    public static function wordwrap_per_line(
14204
        string $str,
14205
        int $width = 75,
14206
        string $break = "\n",
14207
        bool $cut = false,
14208
        bool $add_final_break = true,
14209
        string $delimiter = null
14210
    ): string {
14211 1
        if ($delimiter === null) {
14212 1
            $strings = \preg_split('/\\r\\n|\\r|\\n/', $str);
14213
        } else {
14214 1
            $strings = \explode($delimiter, $str);
14215
        }
14216
14217 1
        $string_helper_array = [];
14218 1
        if ($strings !== false) {
14219 1
            foreach ($strings as $value) {
14220 1
                $string_helper_array[] = self::wordwrap($value, $width, $break, $cut);
14221
            }
14222
        }
14223
14224 1
        if ($add_final_break) {
14225 1
            $final_break = $break;
14226
        } else {
14227 1
            $final_break = '';
14228
        }
14229
14230 1
        return \implode($delimiter ?? "\n", $string_helper_array) . $final_break;
14231
    }
14232
14233
    /**
14234
     * Returns an array of Unicode White Space characters.
14235
     *
14236
     * @psalm-pure
14237
     *
14238
     * @return string[]
14239
     *                  <p>An array with numeric code point as key and White Space Character as value.</p>
14240
     */
14241
    public static function ws(): array
14242
    {
14243 2
        return self::$WHITESPACE;
14244
    }
14245
14246
    /**
14247
     * Checks whether the passed string contains only byte sequences that are valid UTF-8 characters.
14248
     *
14249
     * EXAMPLE: <code>
14250
     * UTF8::is_utf8_string('Iñtërnâtiônàlizætiøn']); // true
14251
     * //
14252
     * UTF8::is_utf8_string("Iñtërnâtiônàlizætiøn\xA0\xA1"); // false
14253
     * </code>
14254
     *
14255
     * @see          http://hsivonen.iki.fi/php-utf8/
14256
     *
14257
     * @param string $str    <p>The string to be checked.</p>
14258
     * @param bool   $strict <p>Check also if the string is not UTF-16 or UTF-32.</p>
14259
     *
14260
     * @psalm-pure
14261
     *
14262
     * @return bool
14263
     *
14264
     * @noinspection ReturnTypeCanBeDeclaredInspection
14265
     */
14266
    private static function is_utf8_string(string $str, bool $strict = false)
14267
    {
14268 110
        if ($str === '') {
14269 15
            return true;
14270
        }
14271
14272 103
        if ($strict) {
14273 2
            $is_binary = self::is_binary($str, true);
14274
14275 2
            if ($is_binary && self::is_utf16($str, false) !== false) {
14276 2
                return false;
14277
            }
14278
14279
            if ($is_binary && self::is_utf32($str, false) !== false) {
14280
                return false;
14281
            }
14282
        }
14283
14284 103
        if (self::$SUPPORT['pcre_utf8']) {
14285
            // If even just the first character can be matched, when the /u
14286
            // modifier is used, then it's valid UTF-8. If the UTF-8 is somehow
14287
            // invalid, nothing at all will match, even if the string contains
14288
            // some valid sequences
14289 103
            return \preg_match('/^./us', $str) === 1;
14290
        }
14291
14292 2
        $mState = 0; // cached expected number of octets after the current octet
14293
        // until the beginning of the next UTF8 character sequence
14294 2
        $mUcs4 = 0; // cached Unicode character
14295 2
        $mBytes = 1; // cached expected number of octets in the current sequence
14296
14297 2
        if (self::$ORD === null) {
14298
            self::$ORD = self::getData('ord');
14299
        }
14300
14301 2
        $len = \strlen($str);
14302
        /** @noinspection ForeachInvariantsInspection */
14303 2
        for ($i = 0; $i < $len; ++$i) {
14304 2
            $in = self::$ORD[$str[$i]];
14305
14306 2
            if ($mState === 0) {
14307
                // When mState is zero we expect either a US-ASCII character or a
14308
                // multi-octet sequence.
14309 2
                if ((0x80 & $in) === 0) {
14310
                    // US-ASCII, pass straight through.
14311 2
                    $mBytes = 1;
14312 2
                } elseif ((0xE0 & $in) === 0xC0) {
14313
                    // First octet of 2 octet sequence.
14314 2
                    $mUcs4 = $in;
14315 2
                    $mUcs4 = ($mUcs4 & 0x1F) << 6;
14316 2
                    $mState = 1;
14317 2
                    $mBytes = 2;
14318 2
                } elseif ((0xF0 & $in) === 0xE0) {
14319
                    // First octet of 3 octet sequence.
14320 2
                    $mUcs4 = $in;
14321 2
                    $mUcs4 = ($mUcs4 & 0x0F) << 12;
14322 2
                    $mState = 2;
14323 2
                    $mBytes = 3;
14324
                } elseif ((0xF8 & $in) === 0xF0) {
14325
                    // First octet of 4 octet sequence.
14326
                    $mUcs4 = $in;
14327
                    $mUcs4 = ($mUcs4 & 0x07) << 18;
14328
                    $mState = 3;
14329
                    $mBytes = 4;
14330
                } elseif ((0xFC & $in) === 0xF8) {
14331
                    /* First octet of 5 octet sequence.
14332
                     *
14333
                     * This is illegal because the encoded codepoint must be either
14334
                     * (a) not the shortest form or
14335
                     * (b) outside the Unicode range of 0-0x10FFFF.
14336
                     * Rather than trying to resynchronize, we will carry on until the end
14337
                     * of the sequence and let the later error handling code catch it.
14338
                     */
14339
                    $mUcs4 = $in;
14340
                    $mUcs4 = ($mUcs4 & 0x03) << 24;
14341
                    $mState = 4;
14342
                    $mBytes = 5;
14343
                } elseif ((0xFE & $in) === 0xFC) {
14344
                    // First octet of 6 octet sequence, see comments for 5 octet sequence.
14345
                    $mUcs4 = $in;
14346
                    $mUcs4 = ($mUcs4 & 1) << 30;
14347
                    $mState = 5;
14348
                    $mBytes = 6;
14349
                } else {
14350
                    // Current octet is neither in the US-ASCII range nor a legal first
14351
                    // octet of a multi-octet sequence.
14352 2
                    return false;
14353
                }
14354 2
            } elseif ((0xC0 & $in) === 0x80) {
14355
14356
                // When mState is non-zero, we expect a continuation of the multi-octet
14357
                // sequence
14358
14359
                // Legal continuation.
14360 2
                $shift = ($mState - 1) * 6;
14361 2
                $tmp = $in;
14362 2
                $tmp = ($tmp & 0x0000003F) << $shift;
14363 2
                $mUcs4 |= $tmp;
14364
                // Prefix: End of the multi-octet sequence. mUcs4 now contains the final
14365
                // Unicode code point to be output.
14366 2
                if (--$mState === 0) {
14367
                    // Check for illegal sequences and code points.
14368
                    //
14369
                    // From Unicode 3.1, non-shortest form is illegal
14370
                    if (
14371 2
                        ($mBytes === 2 && $mUcs4 < 0x0080)
14372
                        ||
14373 2
                        ($mBytes === 3 && $mUcs4 < 0x0800)
14374
                        ||
14375 2
                        ($mBytes === 4 && $mUcs4 < 0x10000)
14376
                        ||
14377 2
                        ($mBytes > 4)
14378
                        ||
14379
                        // From Unicode 3.2, surrogate characters are illegal.
14380 2
                        (($mUcs4 & 0xFFFFF800) === 0xD800)
14381
                        ||
14382
                        // Code points outside the Unicode range are illegal.
14383 2
                        ($mUcs4 > 0x10FFFF)
14384
                    ) {
14385
                        return false;
14386
                    }
14387
                    // initialize UTF8 cache
14388 2
                    $mState = 0;
14389 2
                    $mUcs4 = 0;
14390 2
                    $mBytes = 1;
14391
                }
14392
            } else {
14393
                // ((0xC0 & (*in) != 0x80) && (mState != 0))
14394
                // Incomplete multi-octet sequence.
14395
                return false;
14396
            }
14397
        }
14398
14399 2
        return $mState === 0;
14400
    }
14401
14402
    /**
14403
     * @param string $str
14404
     * @param bool   $use_lowercase      <p>Use uppercase by default, otherwise use lowercase.</p>
14405
     * @param bool   $use_full_case_fold <p>Convert not only common cases.</p>
14406
     *
14407
     * @psalm-pure
14408
     *
14409
     * @return string
14410
     *
14411
     * @noinspection ReturnTypeCanBeDeclaredInspection
14412
     */
14413
    private static function fixStrCaseHelper(
14414
        string $str,
14415
        bool $use_lowercase = false,
14416
        bool $use_full_case_fold = false
14417
    ) {
14418 33
        $upper = self::$COMMON_CASE_FOLD['upper'];
14419 33
        $lower = self::$COMMON_CASE_FOLD['lower'];
14420
14421 33
        if ($use_lowercase) {
14422 2
            $str = \str_replace(
14423 2
                $upper,
14424 2
                $lower,
14425 2
                $str
14426
            );
14427
        } else {
14428 31
            $str = \str_replace(
14429 31
                $lower,
14430 31
                $upper,
14431 31
                $str
14432
            );
14433
        }
14434
14435 33
        if ($use_full_case_fold) {
14436
            /**
14437
             * @psalm-suppress ImpureStaticVariable
14438
             *
14439
             * @var array<mixed>|null
14440
             */
14441 31
            static $FULL_CASE_FOLD = null;
14442 31
            if ($FULL_CASE_FOLD === null) {
14443 1
                $FULL_CASE_FOLD = self::getData('caseFolding_full');
14444
            }
14445
14446 31
            if ($use_lowercase) {
14447 2
                $str = \str_replace($FULL_CASE_FOLD[0], $FULL_CASE_FOLD[1], $str);
14448
            } else {
14449 29
                $str = \str_replace($FULL_CASE_FOLD[1], $FULL_CASE_FOLD[0], $str);
14450
            }
14451
        }
14452
14453 33
        return $str;
14454
    }
14455
14456
    /**
14457
     * get data from "/data/*.php"
14458
     *
14459
     * @param string $file
14460
     *
14461
     * @psalm-pure
14462
     *
14463
     * @return array
14464
     *
14465
     * @noinspection ReturnTypeCanBeDeclaredInspection
14466
     */
14467
    private static function getData(string $file)
14468
    {
14469
        /** @noinspection PhpIncludeInspection */
14470
        /** @noinspection UsingInclusionReturnValueInspection */
14471
        /** @psalm-suppress UnresolvableInclude */
14472 6
        return include __DIR__ . '/data/' . $file . '.php';
14473
    }
14474
14475
    /**
14476
     * @psalm-pure
14477
     *
14478
     * @return true|null
14479
     */
14480
    private static function initEmojiData()
14481
    {
14482 12
        if (self::$EMOJI_KEYS_CACHE === null) {
14483 1
            if (self::$EMOJI === null) {
14484 1
                self::$EMOJI = self::getData('emoji');
14485
            }
14486
14487
            /**
14488
             * @psalm-suppress ImpureFunctionCall - static sort function is used
14489
             */
14490 1
            \uksort(
14491 1
                self::$EMOJI,
14492
                static function (string $a, string $b): int {
14493 1
                    return \strlen($b) <=> \strlen($a);
14494 1
                }
14495
            );
14496
14497 1
            self::$EMOJI_KEYS_CACHE = \array_keys(self::$EMOJI);
14498 1
            self::$EMOJI_VALUES_CACHE = self::$EMOJI;
14499
14500 1
            foreach (self::$EMOJI_KEYS_CACHE as $key) {
14501 1
                $tmp_key = \crc32($key);
14502 1
                self::$EMOJI_KEYS_REVERSIBLE_CACHE[] = '_-_PORTABLE_UTF8_-_' . $tmp_key . '_-_' . \strrev((string) $tmp_key) . '_-_8FTU_ELBATROP_-_';
14503
            }
14504
14505 1
            return true;
14506
        }
14507
14508 12
        return null;
14509
    }
14510
14511
    /**
14512
     * Checks whether mbstring "overloaded" is active on the server.
14513
     *
14514
     * @psalm-pure
14515
     *
14516
     * @return bool
14517
     *
14518
     * @noinspection ReturnTypeCanBeDeclaredInspection
14519
     */
14520
    private static function mbstring_overloaded()
14521
    {
14522
        /**
14523
         * INI directive 'mbstring.func_overload' is deprecated since PHP 7.2
14524
         */
14525
14526
        /** @noinspection PhpComposerExtensionStubsInspection */
14527
        /** @noinspection PhpUsageOfSilenceOperatorInspection */
14528
        return \defined('MB_OVERLOAD_STRING')
14529
               &&
14530
               ((int) @\ini_get('mbstring.func_overload') & \MB_OVERLOAD_STRING);
14531
    }
14532
14533
    /**
14534
     * @param array    $strings
14535
     * @param bool     $remove_empty_values
14536
     * @param int|null $remove_short_values
14537
     *
14538
     * @psalm-pure
14539
     *
14540
     * @return array
14541
     *
14542
     * @noinspection ReturnTypeCanBeDeclaredInspection
14543
     */
14544
    private static function reduce_string_array(
14545
        array $strings,
14546
        bool $remove_empty_values,
14547
        int $remove_short_values = null
14548
    ) {
14549
        // init
14550 2
        $return = [];
14551
14552 2
        foreach ($strings as &$str) {
14553
            if (
14554 2
                $remove_short_values !== null
14555
                &&
14556 2
                \mb_strlen($str) <= $remove_short_values
14557
            ) {
14558 2
                continue;
14559
            }
14560
14561
            if (
14562 2
                $remove_empty_values
14563
                &&
14564 2
                \trim($str) === ''
14565
            ) {
14566 2
                continue;
14567
            }
14568
14569 2
            $return[] = $str;
14570
        }
14571
14572 2
        return $return;
14573
    }
14574
14575
    /**
14576
     * rxClass
14577
     *
14578
     * @param string $s
14579
     * @param string $class
14580
     *
14581
     * @psalm-pure
14582
     *
14583
     * @return string
14584
     *
14585
     * @noinspection ReturnTypeCanBeDeclaredInspection
14586
     */
14587
    private static function rxClass(string $s, string $class = '')
14588
    {
14589
        /**
14590
         * @psalm-suppress ImpureStaticVariable
14591
         *
14592
         * @var array<string,string>
14593
         */
14594 33
        static $RX_CLASS_CACHE = [];
14595
14596 33
        $cache_key = $s . '_' . $class;
14597
14598 33
        if (isset($RX_CLASS_CACHE[$cache_key])) {
14599 21
            return $RX_CLASS_CACHE[$cache_key];
14600
        }
14601
14602
        /** @var string[] $class_array */
14603 16
        $class_array[] = $class;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$class_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $class_array = array(); before regardless.
Loading history...
14604
14605
        /** @noinspection SuspiciousLoopInspection */
14606
        /** @noinspection AlterInForeachInspection */
14607 16
        foreach (self::str_split($s) as &$s) {
0 ignored issues
show
Bug introduced by
The expression self::str_split($s) cannot be used as a reference.

Let?s assume that you have the following foreach statement:

foreach ($array as &$itemValue) { }

$itemValue is assigned by reference. This is possible because the expression (in the example $array) can be used as a reference target.

However, if we were to replace $array with something different like the result of a function call as in

foreach (getArray() as &$itemValue) { }

then assigning by reference is not possible anymore as there is no target that could be modified.

Available Fixes

1. Do not assign by reference
foreach (getArray() as $itemValue) { }
2. Assign to a local variable first
$array = getArray();
foreach ($array as &$itemValue) {}
3. Return a reference
function &getArray() { $array = array(); return $array; }

foreach (getArray() as &$itemValue) { }
Loading history...
14608 15
            if ($s === '-') {
14609
                $class_array[0] = '-' . $class_array[0];
14610 15
            } elseif (!isset($s[2])) {
14611 15
                $class_array[0] .= \preg_quote($s, '/');
14612 1
            } elseif (self::strlen($s) === 1) {
14613 1
                $class_array[0] .= $s;
14614
            } else {
14615 15
                $class_array[] = $s;
14616
            }
14617
        }
14618
14619 16
        if ($class_array[0]) {
14620 16
            $class_array[0] = '[' . $class_array[0] . ']';
14621
        }
14622
14623 16
        if (\count($class_array) === 1) {
14624 16
            $return = $class_array[0];
14625
        } else {
14626
            $return = '(?:' . \implode('|', $class_array) . ')';
14627
        }
14628
14629 16
        $RX_CLASS_CACHE[$cache_key] = $return;
14630
14631 16
        return $return;
14632
    }
14633
14634
    /**
14635
     * Personal names such as "Marcus Aurelius" are sometimes typed incorrectly using lowercase ("marcus aurelius").
14636
     *
14637
     * @param string $names
14638
     * @param string $delimiter
14639
     * @param string $encoding
14640
     *
14641
     * @psalm-pure
14642
     *
14643
     * @return string
14644
     *
14645
     * @noinspection ReturnTypeCanBeDeclaredInspection
14646
     */
14647
    private static function str_capitalize_name_helper(
14648
        string $names,
14649
        string $delimiter,
14650
        string $encoding = 'UTF-8'
14651
    ) {
14652
        // init
14653 1
        $name_helper_array = \explode($delimiter, $names);
14654 1
        if ($name_helper_array === false) {
14655
            return '';
14656
        }
14657
14658
        $special_cases = [
14659 1
            'names' => [
14660
                'ab',
14661
                'af',
14662
                'al',
14663
                'and',
14664
                'ap',
14665
                'bint',
14666
                'binte',
14667
                'da',
14668
                'de',
14669
                'del',
14670
                'den',
14671
                'der',
14672
                'di',
14673
                'dit',
14674
                'ibn',
14675
                'la',
14676
                'mac',
14677
                'nic',
14678
                'of',
14679
                'ter',
14680
                'the',
14681
                'und',
14682
                'van',
14683
                'von',
14684
                'y',
14685
                'zu',
14686
            ],
14687
            'prefixes' => [
14688
                'al-',
14689
                "d'",
14690
                'ff',
14691
                "l'",
14692
                'mac',
14693
                'mc',
14694
                'nic',
14695
            ],
14696
        ];
14697
14698 1
        foreach ($name_helper_array as &$name) {
14699 1
            if (\in_array($name, $special_cases['names'], true)) {
14700 1
                continue;
14701
            }
14702
14703 1
            $continue = false;
14704
14705 1
            if ($delimiter === '-') {
14706
                /** @noinspection AlterInForeachInspection */
14707 1
                foreach ((array) $special_cases['names'] as &$beginning) {
14708 1
                    if (\strncmp($name, $beginning, \strlen($beginning)) === 0) {
14709 1
                        $continue = true;
14710
14711 1
                        break;
14712
                    }
14713
                }
14714
            }
14715
14716
            /** @noinspection AlterInForeachInspection */
14717 1
            foreach ((array) $special_cases['prefixes'] as &$beginning) {
14718 1
                if (\strncmp($name, $beginning, \strlen($beginning)) === 0) {
14719 1
                    $continue = true;
14720
14721 1
                    break;
14722
                }
14723
            }
14724
14725 1
            if ($continue) {
14726 1
                continue;
14727
            }
14728
14729 1
            $name = self::ucfirst($name);
14730
        }
14731
14732 1
        return \implode($delimiter, $name_helper_array);
14733
    }
14734
14735
    /**
14736
     * Generic case-sensitive transformation for collation matching.
14737
     *
14738
     * @param string $str <p>The input string</p>
14739
     *
14740
     * @psalm-pure
14741
     *
14742
     * @return string|null
14743
     */
14744
    private static function strtonatfold(string $str)
14745
    {
14746 6
        $str = \Normalizer::normalize($str, \Normalizer::NFD);
14747
        /** @phpstan-ignore-next-line - https://github.com/JetBrains/phpstorm-stubs/pull/949 */
14748 6
        if ($str === false) {
14749 2
            return '';
14750
        }
14751
14752
        /** @noinspection PhpUndefinedClassInspection */
14753 6
        return \preg_replace(
14754 6
            '/\p{Mn}+/u',
14755 6
            '',
14756 6
            $str
14757
        );
14758
    }
14759
14760
    /**
14761
     * @param int|string $input
14762
     *
14763
     * @psalm-pure
14764
     *
14765
     * @return string
14766
     *
14767
     * @noinspection ReturnTypeCanBeDeclaredInspection
14768
     * @noinspection SuspiciousBinaryOperationInspection
14769
     */
14770
    private static function to_utf8_convert_helper($input)
14771
    {
14772
        // init
14773 32
        $buf = '';
14774
14775 32
        if (self::$ORD === null) {
14776 1
            self::$ORD = self::getData('ord');
14777
        }
14778
14779 32
        if (self::$CHR === null) {
14780 1
            self::$CHR = self::getData('chr');
14781
        }
14782
14783 32
        if (self::$WIN1252_TO_UTF8 === null) {
14784 1
            self::$WIN1252_TO_UTF8 = self::getData('win1252_to_utf8');
14785
        }
14786
14787 32
        $ordC1 = self::$ORD[$input];
14788 32
        if (isset(self::$WIN1252_TO_UTF8[$ordC1])) { // found in Windows-1252 special cases
14789 32
            $buf .= self::$WIN1252_TO_UTF8[$ordC1];
14790
        } else {
14791
            /** @noinspection OffsetOperationsInspection */
14792 1
            $cc1 = self::$CHR[$ordC1 / 64] | "\xC0";
14793 1
            $cc2 = ((string) $input & "\x3F") | "\x80";
0 ignored issues
show
Bug introduced by
Are you sure you want to use the bitwise & or did you mean &&?
Loading history...
Bug introduced by
Are you sure you want to use the bitwise | or did you mean ||?
Loading history...
14794 1
            $buf .= $cc1 . $cc2;
14795
        }
14796
14797 32
        return $buf;
14798
    }
14799
14800
    /**
14801
     * @param string $str
14802
     *
14803
     * @psalm-pure
14804
     *
14805
     * @return string
14806
     *
14807
     * @noinspection ReturnTypeCanBeDeclaredInspection
14808
     */
14809
    private static function urldecode_unicode_helper(string $str)
14810
    {
14811 10
        $pattern = '/%u([0-9a-fA-F]{3,4})/';
14812 10
        if (\preg_match($pattern, $str)) {
14813 7
            $str = (string) \preg_replace($pattern, '&#x\\1;', $str);
14814
        }
14815
14816 10
        return $str;
14817
    }
14818
}
14819